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;      
        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/

相关文章:

python - Python和Haskell有C/C++的 float 不确定性问题吗?

c++ - 关于 C++ 友元声明中没有返回类型的意外错误

c++ - 好友定义不适用于 gcc4.9

c++ - openGL 中的全屏

c++ - 如何获得重载解析选择的仿函数签名?

c++ - GLSL/C++ 中的白色(可能未着色)OBJ

c++ - 运算符作为友元重载函数?

c++ - 在 Eclipse 中对 STL 容器进行合理调试

c++ - 友元函数和声明

c++ - 跨命名空间和不同 .H 文件的友元类