【问题标题】:Why friend function without argument is not working?为什么没有参数的朋友功能不起作用?
【发布时间】:2021-07-05 05:16:25
【问题描述】:
 #include<iostream>
    using namespace std;
    
    class complex{
        private:
        int x;
    
        public:
        friend void fun(void);
    };
    
    void fun(void)
    {
        cout<<"outside "<<endl;
    }
    int main()
    {
        complex c1;
        c1.fun();
        return 0;
    }

为什么我收到以下错误,指出“类复合体”在 VS 代码中没有名为“fun”的成员

36_friend_function.cpp: In function 'int main()':
36_friend_function.cpp:19:8: error: 'class complex' has no member named 'fun'
     c1.fun();
        ^~~

【问题讨论】:

  • 请解释您的目标,而不仅仅是您遇到的症状

标签: c++ class friend-function


【解决方案1】:

函数fun 是complex 的朋友,这意味着它可以使用该对象的内部。但是它不是对象的一部分,所以你不能通过对象调用它。

您必须像调用任何其他函数一样调用fun

例子:

void fun(complex &c)
{
    // fun is a friend so it can access private member x.
    cout << "outside " << c.x << endl;
}

int main()
{
    complex c1;
    fun(c1);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    相关资源
    最近更新 更多