如何只为一个特定的函数和类声明友元函数?
我的代码有什么问题吗?
我尝试在 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;
}
What's wrong with my code?
I tried to compile the code below in the GNU G++ environment and I get these errors:
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
成员函数必须首先在其类中声明(而不是在友元声明中)。这必定意味着在友元声明之前,您应该定义它的类 - 仅仅前向声明是不够的。
A member function must be first declared in its class (not in a friend declaration). That must mean that prior to the friend declaration, you should have the class of it defined - a mere forward declaration does not suffice.