下面代碼實現+、()、=的運算符重載,僅供參考。
#include <iostream>
class Body{
public:
Body(int a = 0):m_a(a) {}
~Body() {}
#include <iostream>
class Body{
public:
Body(int a = 0):m_a(a) {}
~Body() {}
Body(const Body& a) {
this -> m_a = a.m_a;
}
// +運算符重載
Body operator+(const Body& a) {
Body bd;
bd.m_a = this -> m_a + a.m_a;
return bd;
}
// ()運算符重載
int operator()(int i) {
return this -> m_a + i;
}
// =運算符重載
Body& operator=(const Body& a) {
this -> m_a = a.m_a;
return *this;
}
int get() {
return m_a;
}
private:
int m_a;
};
int main(int argc, char** args) {
Body a(1);
Body b(100);
Body result = a = b;
std::cout << "a: " << result.get() << std::endl;
std::cout << (a + b).get() << std::endl;
std::cout << a(999) << std::endl;
return 0;
}