qfedu-cpp-level/day4/d8.cpp

42 lines
583 B
C++
Raw Permalink Normal View History

// 运算符重载
// + 运算符
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class A
{
private:
int x;
public:
explicit A(int x)
{
this->x = x;
}
void show()
{
cout << x << endl;
}
// + 运算符重载,类成员函数,双目运算符,只需要一个参数
A *operator+(A &other);
};
A *A::operator+(A &other)
{
A *tmp = new A(this->x + other.x);
return tmp;
}
int main()
{
A a1(5), a2(6);
a1.show();
A *a3 = a1 + a2;
a3->show();
delete a3;
return 0;
}