首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >朋友函数C++

朋友函数C++
EN

Stack Overflow用户
提问于 2013-12-07 18:44:21
回答 3查看 197关注 0票数 1

为什么这个不行?

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

代码语言:javascript
复制
#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;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-07 18:47:49

四个问题:

  1. 您已经在构造函数中定义了朋友函数。把它移到外面,这样它就有它自己的功能了。
  2. std:ostream替换为std::ostream
  3. 交换参数的顺序。
  4. return os<<c.x之后添加分号

最终结果:

代码语言:javascript
复制
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;
    }
};
票数 3
EN

Stack Overflow用户

发布于 2013-12-07 18:47:12

代码语言:javascript
复制
    friend std:ostream & operator<<(const Circle & c, std::ostream & os)
    {
        return os<<c.x
    }

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

票数 1
EN

Stack Overflow用户

发布于 2013-12-07 18:48:06

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20445096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档