我想将一个类的方法设为友元,而不是将整个类设为友元。 这是我的东西
class tar;
class foo
{
private:
int foo_int;
public:
foo(){std::cout << "Constructor\n";}
friend void tar::anotherMethod();
};
class tar
{
public:
void anotherMethod()
{
foo f;
f.foo_int = 13;
std::cout << f.foo_int;
}
};
这些是我得到的错误
error C2027: use of undefined type 'tar'
error C2248: 'foo::foo_int' : cannot access private member declared in class 'foo'
对我可能做错了什么有什么建议吗?
最佳答案
为了使您的代码能够通过编译,您可以重新安排声明和定义:
#include <iostream>
class tar
{
public:
void anotherMethod();
};
class foo
{
private:
int foo_int;
public:
foo(){std::cout << "Constructor\n";}
friend void tar::anotherMethod();
};
void tar::anotherMethod()
{
foo f;
f.foo_int = 13;
std::cout << f.foo_int;
}
关于c++ - 将类的方法作为 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26394397/