C++学习笔记之运算符重载(加号+, 递增运算符++,–,左移运算符重载)C++运算符重载 运算符重载
概念:
对已有的运算符重载重新进行定义,赋予其另一种功能以适应不同的数据类型
加号运算符重载
作用:实现两个自定义数据类型相加的运算
成员函数实现 + 号运算符重载
Person operator + (const Person & p)
//对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
//实现两个自定义数据类型相加的运算
#include <iostream>
using namespace std;
class Person {
public:
Person() {
cout << "这是一个默认构造函数" << endl;
m_A = 0;
m_B = 0;
}
Person(int a, int b): m_A(a), m_B(b){
cout << "这是一个用户自定义构造函数" << endl;
}
//成员函数重载+号
Person operator+(const Person& p) {
Person temp(0,0);
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}
void ShowInfo() {
cout << "m_A = " << this->m_A << endl;
cout << "m_B = " << this->m_B << endl;
}
public:
int m_A;
int m_B;
};
void test00() {
Person p1(10, 20);
Person p2(20, 30);
Person p3 = p1 + p2;
p3.ShowInfo();
p3 = p3 + p2;
p3.ShowInfo();
}
int main() {
test00();
return 0;
}
全局函数实现 + 号运算符重载
Person operator+(const Person& p1, const Person& p2)
左移运算符重载
作用: 可以输出自定义数据类型
只能利用全局函数重载左移运算符
void operator << (ostream& cout, Person& p) //本质operator<<(cout, p)
重载左移运算符配合友元实现输出自定义类型
//左移运算符重载
//作用:可以输出自定义类型
#include <iostream>
using namespace std;
class Person {
friend ostream& operator<< (ostream& out, Person& p);
public:
Person(int a, int b) {
this->m_A = a;
this->m_B = b;
}
//成员函数无法实现 p << cout 不是我们想要的效果
//void operator<< (Person& p){
//}
private:
int m_A;
int m_B;
};
//全局函数实现左移重载
//ostream 对象只能有一个
ostream& operator<<(ostream& out, Person& p) {
out << "m_A : " << p.m_A << "m_B = " << p.m_B << endl;
return out;
}
void test00() {
Person p(10,20);
cout << p << endl;
}
int main() {
test00();
return 0;
}
递增运算符重载
作用: 通过重载递增运算符,实现自己的整型数据
重载前置++运算符
MyInterger& operator++() {}
返回引用是为了一直对一个数据进行递增操作
重载后置++运算符
MyInterger& operator++(int ) {} 占位参数
#include <iostream>
using namespace std;
//通过重载递增运算符,实现自己整形数据
class MyInteger {
friend ostream& operator<< (ostream& out, MyInteger myint);
public:
MyInteger(){
m_Num = 5;
}
//前置++
MyInteger& operator++() {
//先++
m_Num++;
return *this;
}
//前置--
MyInteger& operator--() {
//先++
m_Num--;
return *this;
}
//后置++
MyInteger operator++(int) {
MyInteger temp = *this;
m_Num++;
return temp; //由于此处为局部变量,所以采用值传递的方式
}
//后置--
MyInteger operator--(int) {
MyInteger temp = *this;
m_Num--;
return temp; //由于此处为局部变量,所以采用值传递的方式
}
private:
int m_Num;
};
ostream& operator<< (ostream& out, MyInteger myint) {
out << "myint.m_Num = " << myint.m_Num << endl;
return out;
}
void test00() {
MyInteger myInt;
cout << "myInt = " <<myInt << endl;
cout << "++myInt = " << ++myInt << endl;
cout << "myInt = " << myInt << endl;
cout << "++(++myInt) = " << ++(++myInt) << endl;
cout << "myInt = " << myInt << endl;
cout << "myInt = " << myInt++ << endl;
cout << 5 << endl;
cout << "--myInt = " << --myInt << endl;
cout << "myInt-- = " << myInt-- << endl;
cout << "myInt = " << myInt << endl;
}
int main() {
test00();
return 0;
}
答案
C++学习笔记之运算符重载(加号+, 递增运算符++,–,左移运算符重载)C++运算符重载 运算符重载