最近做了一道题目,运用到了c++的<<运算符重载,报错好久才解决,这里进行一个总结
一.运算符重载的两种方式
1.成员函数
class Animal {
private:
int age;
string name;
string interests;
public:
Animal(int age, string name, string interests)
{
this->age = age;
this->name = name;
this->interests = interests;
}
// 加号运算符重载
Animal operator+(const Animal& a)
{
Animal temp(this->age + a.age, this->name, a.interests);
return temp;
}
Animal(const Animal& a)
{
cout << "Animal类的拷贝构造函数被调用" << endl;
this->age = a.age;
this->name = a.name;
this->interests = a.interests;
}
};
void test01()
{
// 加号运算符重载
Animal a1(10, "熊大", "跑步");
Animal a2(9, "熊二", "吃蜂蜜");
Animal a3 = a1 + a2;
}
坑:函数运算符重载的时候以Animal &的形式返回引用,导致程序崩溃,我猜测是因为这样会返回临时对象temp的引用,导致空引用的情况发生。
2.友元函数(全局函数)
class Animal {
private:
int age;
string name;
string interests;
public:
//声明为友元函数
friend Animal operator+(const Animal& a, const Animal& b);
Animal(int age, string name, string interests)
{
this->age = age;
this->name = name;
this->interests = interests;
}
};
Animal operator+(const Animal& a, const Animal& b) {
Animal temp(a.age + b.age, a.name, b.interests);
return temp;
}
void test01()
{
// 输入运算符重载
Animal a();
// 加号运算符重载
Animal a1(10, "熊大", "跑步");
Animal a2(9, "熊二", "吃蜂蜜");
Animal a3 = a1 + a2;
}
二.特殊的运算符重载
右移运算符重载
右移运算符的重载只能采用全局函数的方式,因为运算符重载实际上是在定义一个函数,如上面Animal类的+运算符重载实际上是定义一个函数名为 + 的函数,成员函数的方式就是定义一个成员函数,友元函数(全局函数)的方式就是定义一个全局函数。如果要给 >>运算符以成员函数的方式进行重载,就意味着要在左操作数 cin 对象的类中实现函数重载,显然是做不到的,所以只能采用全局函数的方式。
class Animal {
private:
int age;
string name;
string interests;
public:
friend istream& operator>>(istream& input, Animal& a);
Animal(int age, string name, string interests)
{
this->age = age;
this->name = name;
this->interests = interests;
}
};
// 左移运算符重载
istream& operator>>(istream& input,Animal &a)
{
cout << "请输入你的姓名:" << endl;
input >> a.name;
cout << "请输入你的年龄:" << endl;
input >> a.age;
cout << "请输入你的兴趣爱好:" << endl;
input >> a.interests;
return input;
}
void test01()
{
// 输入运算符重载
Animal a(10, "yiyi", "打游戏");
cin >> a;
}
坑:第一个参数应该是 istream & 类型,而不是上const istream &,一个合理的解释是输入操作符会改变流的状态。
坑:需要将该运算符重载的函数声明为Animal类的友元函数,这样才能访问Animal类的私有成员。