小胡不糊涂123 2023-03-20 11:34 采纳率: 95.2%
浏览 18
已结题

C++中的友元函数和命名空间

这是正确的代码:

#include<iostream>

class Point
{
private:
    int x, y;
public:
    
    void set(int a, int b)
    {
        x = a;
        y = b;
    }
    void show()
    {
        std::cout << "(" << x << "," << y << ")"<<std::endl;
    }

    friend Point operator-(const Point& p2);
};

Point operator-(const Point& p2)
{
    Point temp;
    temp.x = -p2.x;
    temp.y = -p2.y;
    return temp;
}

int main()
{
    int a = 10;
    Point p1;
    p1.set(1, 2);
    p1.show();
    Point p2 = operator-(p1);
    p2.show();
    
    system("pause");
    return 0;
}

这是错误的代码:

#include<iostream>
using namespace std;

class Point
{
private:
    int x, y;
public:
    
    void set(int a, int b)
    {
        x = a;
        y = b;
    }
    void show()
    {
        cout << "(" << x << "," << y << ")"<<endl;
    }

    friend Point operator-(const Point& p2);
};

Point operator-(const Point& p2)
{
    Point temp;
    temp.x = -p2.x;
    temp.y = -p2.y;
    return temp;
}

int main()
{
    int a = 10;
    Point p1;
    p1.set(1, 2);
    p1.show();
    Point p2 = operator-(p1);
    p2.show();
    
    system("pause");
    return 0;
}

在VS2022上都可以通过,但是用devc++或者vc++错误代码就通过不了,只是在开头加了一句命名空间为什么会报错?
友元函数和命名空间冲突吗?还是不同编译器的问题?

下面是报错原因:
INTERNAL COMPILER ERROR
(compiler file 'msc1.cpp', line 1786)
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information

  • 写回答

4条回答 默认 最新

  • 小胡不糊涂123 2023-03-22 19:26
    关注

    查了一下,是因为编译器太老了,C++的标准不全,所以这个版本的运算符重载函数是不能用友元的,语法什么的没问题

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月22日
  • 已采纳回答 3月22日
  • 创建了问题 3月20日

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题