繁体   English   中英

制作类的朋友方法

[英]Making methods of a class as a 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM