C++ 将类的方法作为朋友
我想把一个班级当作朋友,而不是把整个班级当作朋友。 这是我的C++ 将类的方法作为朋友,c++,friend,C++,Friend,我想把一个班级当作朋友,而不是把整个班级当作朋友。 这是我的 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;
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;
}
};
关于我可能做错了什么有什么建议吗?在另一种情况下,为了使代码能够编译,您可以重新排列声明和定义:
#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;
}
#包括
等级焦油
{
公众:
void-anotherMethod();
};
福班
{
私人:
int foo_int;
公众:
foo(){std::cout:在定义类型之前不能使用它。要解决此错误,请确保在引用它之前已完全定义该类型。
。我将类tar
声明为原型。我无法理解为什么不选择它。这解释得更好一些。让全班同学成为朋友以避免头痛。我知道我可以这样做,但我正在尝试让方法friend OnlyTanks获得回复。我知道您重新安排了此方法以获得识别的类型。当我替换friend void tar::anotherMethod()时,我不明白为什么编译器可以使用该类型
使用友元类tar
@MistyD:因为它知道tar
是一个类(您之前声明过它),但在看到成员函数的定义之前,它不知道是否会有成员tar::anotherMethod()
。
#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;
}