我的代码有什么问题?
我试图在 GNU G++ 环境中编译下面的代码,但出现了这些错误:
friend2.cpp:30: error: invalid use of incomplete type ‘struct two’ friend2.cpp:5: error: forward declaration of ‘struct two’ friend2.cpp: In member function ‘int two::accessboth(one)’: friend2.cpp:24: error: ‘int one::data1’ is private friend2.cpp:55: error: within this context
#include <iostream>
using namespace std;
class two;
class one
{
private:
int data1;
public:
one()
{
data1 = 100;
}
friend int two::accessboth(one a);
};
class two
{
private:
int data2;
public:
two()
{
data2 = 200;
}
int accessboth(one a);
};
int two::accessboth(one a)
{
return (a.data1 + (*this).data2);
}
int main()
{
one a;
two b;
cout << b.accessboth(a);
return 0;
}
最佳答案
成员函数必须首先在其类中声明(而不是在友元声明中)。这一定意味着在 friend 声明之前,你应该定义它的类——仅仅一个前向声明是不够的。
class one;
class two
{
private:
int data2;
public:
two()
{
data2 = 200;
}
// this goes fine, because the function is not yet defined.
int accessboth(one a);
};
class one
{
private:
int data1;
public:
one()
{
data1 = 100;
}
friend int two::accessboth(one a);
};
// don't forget "inline" if the definition is in a header.
inline int two::accessboth(one a) {
return (a.data1 + (*this).data2);
}
关于c++ - 如何只为一个特定的函数和类声明友元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966255/