这是正确的代码:
#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