好友函数C++

好友函数C++,c++,class,C++,Class,为什么这样不行 我在代码中使用了友好函数,但有一个错误,所以我找不到它。请帮忙 #include<iostream> #include<cstdlib> using namespace std; class Circle{ private: int x; public: Circle(int x1=5){ x=x1; friend std:ostream & operator<<(const Circle

为什么这样不行

我在代码中使用了友好函数,但有一个错误,所以我找不到它。请帮忙

#include<iostream>
#include<cstdlib>
using namespace std;
class Circle{
private:
    int x;
public:
    Circle(int x1=5){
        x=x1;
        friend std:ostream & operator<<(const Circle & c, std::ostream & os)
        {
            return os<<c.x
        }
    }
};
int main()
{
    Circle s;
    cout<< s;
    system("pause");
    return 0;
}
您应该在构造函数之外声明此函数

您应该在构造函数之外声明此函数。

有四个问题:

您已经在构造函数中定义了friend函数。将其移到外部,使其具有自己的功能

将std:ostream替换为std::ostream

交换参数的顺序

在return os4个问题后添加分号:

您已经在构造函数中定义了friend函数。将其移到外部,使其具有自己的功能

将std:ostream替换为std::ostream

交换参数的顺序


在return os后添加分号友元函数需要在与构造函数相同的级别上声明,而不是在构造函数内部声明。

友元函数需要在与构造函数相同的级别上声明,而不是在构造函数内部声明。

另一个小细节:在ossorry之后缺少分号,我刚刚从@Mat发布的代码中复制了这个函数,在这个函数中还有另外两个错误,我没有标记它是osorry后面的分号,还有一个小细节:在osorry后面缺少分号,我只是从@Mat发布的代码中复制了这个函数,在这个函数中还有两个错误,我没有标记,那就是os后面的分号
    friend std:ostream & operator<<(const Circle & c, std::ostream & os)
    {
        return os<<c.x
    }
class Circle{
private:
    int x;
public:
    Circle(int x1=5){
        x=x1;
    }
    friend std::ostream & operator<<(std::ostream & os, const Circle & c)
    {
        return os<<c.x;
    }
};