C++编译出错,请帮忙修改!

来源:百度知道 编辑:UC知道 时间:2024/06/06 15:09:53
/* 程序10.6:负号运算符全局函数重载.cpp:*/
#include<iostream> //包含头文件
using namespace std; //使用名字空间std
class Person //声明一个类Person
{
friend void operator-(Person); //声明负号运算符函数为友员函数
private:
int iApple; //声明私有成员变量
public:
Person(int iApple); //声明构造符函数
void operator -(); //声明负号运算符函数
void display(); //声明显示成员变量函数
};
void operator-(Person); //声明负号运算符函数原型

int main() //main()函数开始
{
Person Xiaowang(5); //声明类对象Xiaowang,自动调用构造符
cout<<"\n调用operator-()负号运算符函数前"<<endl;
Xiaowang.display(); //调用显示成员变量函数
-Xiaowang; //等价于operator-(Xiaowang)
cout<<"\n调用operator-()负号运算符函数后"<<endl;
Xiaowang.display(); //调用显示成员变量函数
return 0;
} //main()函数结束

Person::Person(int iApple) //定义构造符函数
{
this->iApple=iApple;
}
void operator-(Person p1) //定义负号运算符函数
{
p1.iApple=-p1.iApple;
}

有2个错:
一、void operator-(); 这个声明是多余的,它和void operator-(Person);有冲突。
二、void operator-(Person);重载函数一般要有返回值,否则iApple值不会发生改变,改的只是括号参数里p1对象的值。

另外有个习惯希望你更正,就是要把main方法写在最下面。
我在VS 2005上测试通过,并改为如下:

#include<iostream> //包含头文件
using namespace std; //使用名字空间std
class Person //声明一个类Person
{
friend Person operator-(Person); //声明负号运算符函数为友员函数
private:
int iApple; //声明私有成员变量
public:
Person(int iApple); //声明构造符函数
//void operator-(); //声明负号运算符函数
void display(); //声明显示成员变量函数
};

Person operator-(Person); //声明负号运算符函数原型

Person::Person(int iApple) //定义构造符函数
{
this->iApple=iApple;
}

Person operator-(Person p1) //定义负号运算符函数
{
p1.iApple=p1.iApple*(-1);
return Person(p1.iApple);
}

void Person::display() //定义显示成员变量函数
{
cout<<" iApple="<<iApple<<endl;
}

int