[英]How can friend function be declared for only one particular function and class?
What's wrong with my code? 我的代码有什么问题?
I tried to compile the code below in the GNU G++ environment and I get these errors: 我尝试在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;
}
A member function must be first declared in its class (not in a friend declaration). 成员函数必须首先在其类中声明(而不是在friend声明中)。 That must mean that prior to the friend declaration, you should have the class of it defined - a mere forward declaration does not suffice. 那必须意味着在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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.