Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

c++ - 在使用另一类C ++的“朋友”功能时找不到错误(Can't spot the mistake in using “friend” function of another class C++)

Yes I know that private modifier created in order to prohibit access to class data

(是的,我知道创建了private修饰符是为了禁止访问类数据)
but isn't friend intended to allow special acces to them?

(但是,难道friend不打算允许他们特殊访问吗?)

Compiler:

(编译器:)
main.cpp: In member function 'void C::blah(B&)':

(main.cpp:在成员函数'void C :: blah(B&)'中:)
main.cpp:48:26: error: 'int B::a' is private within this context

(main.cpp:48:26:错误:'int B :: a'在此上下文中是私有的)
std::cout << obj.a << std::endl;

(std :: cout << obj.a << std :: endl;)

Everything below is implemented the way as it is in many tutorials.

(下面的所有内容都是按照许多教程中的方式实现的。)
May be it's just silly mistake I made and blind to spot.

(可能只是我犯的愚蠢错误而盲目发现。)

Class C;

class B {
private:

    int a = 2;

public:

    friend void blah(B& obj);

};

class C {
public:

    void blah(B& obj) {
        std::cout << obj.a << std::endl;  //*
    }

};

*Member B::a is inaccessible

(*成员B :: a无法访问)

  ask by Vladislav translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're declaring a non-member function named blah , but not C::blah as friend .

(您要声明一个名为blah的非成员函数,但不能将C::blahfriend 。)

You could change your code to the following, and note the order of the declaration and definition.

(您可以将代码更改为以下代码,并注意声明和定义的顺序。)

class B;

class C {
public:
    void blah(B& obj);
};

class B {
private:
    int a = 2;
public:
    friend void C::blah(B& obj);
};

void C::blah(B& obj) {
    std::cout << obj.a << std::endl;
}

LIVE

(生活)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...