友元函数前的不合格 id

unqualified id before a friend function

我收到以下错误:

..\src\test.cpp:17:20: error: expected unqualified-id before 'try'
         friend int try(Complex);

请帮忙告诉我为什么这段代码会产生错误:

#include <iostream>
using namespace std;
class Complex
{
private:
    int a, b;
public:
    showData()
    {   
        cout<<"\na= "<<a<<" b= "<<b;
    }
    Complex(int x, int y)
    { //constructer
        a = x;
        b = y;
    }
    friend int try(Complex);
    //friend function
};
int try(Complex c)
{   
    cout<<"You areworking in try now";
    cout<<"\noutput from friend fun : "<<c.a<<" "<<c.b;
}
int main()
{
    Complex c1(3, 4);
    try(c1);
    return 0;
}

首先让我们将问题简化为 Minimal Complete and Verifiable example 重复问题:

int try;

不需要太多代码,因为 try is a reserved word. You cannot use try in a program without the compiler expecting a try/catch` block

解决方案:不要使用 try 作为标识符。而是使用 try_func 或描述正在尝试的内容。

补充说明:showData() 需要 return 类型。最有可能应该是 void showData()