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

这是正确的代码:

#include

class Point
{
private:
    int x, y;
public:
    
    void set(int a, int b)
    {
        x = a;
        y = b;
    }
    void show()
    {
        std::cout << "(" << x << "," << y << ")"<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
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 << ")"<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

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

参考GPT和自己的思路:

对于错误的代码,问题出在使用了命名空间std,而在友元函数中没有加上命名空间,因此在不同编译器中表现不同。正确的做法应该是在友元函数中也加上命名空间std,如下所示:

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

这样代码就可以在不同编译器中正常运行。至于为什么会出现这种情况,可能是不同编译器对命名空间和友元函数的处理方式略有不同。建议使用标准写法避免这种问题的出现。

参考GPT和自己的思路:

关于你的问题,我可以给出以下解释:

  1. 命名空间的问题:在错误的代码中,添加了命名空间std,但是没有在代码中使用它。这导致了错误,因为命名空间std定义了很多与C++相关的函数和类,并且可能与你的代码中定义的名称冲突。因此,添加命名空间std后,你需要使用std来引用相关的函数或类,例如cout和endl。

  2. 编译器问题:不同的编译器可能会有不同的规则和实现方式,导致同样的代码在不同的编译器上的编译结果不同。在这种情况下,这可能是由于编译器使用的不同的标准或实现方式导致的。

总之,在C++中,友元函数和命名空间并不会冲突,但是需要正确使用和引用。如果你的代码在某些编译器上无法通过,你可以尝试不同的编译器或者检查代码是否符合C++标准的规范。