- +,- 运算符重载
#include
class Complex{
public:
Complex(int x, int y):a(x), b(y){};
~Complex(){};
Complex operator - (const Complex &c);
int a;
int b;
};
Complex operator + (const Complex &x, const Complex &y){
return Complex(x.a + y.a, x.b + y.b);
}
Complex Complex::operator - (const Complex &c){
a = a - c.a;
b = b - c.b;
return *this;
}
int main(){
Complex test_a(8,9);
Complex text_b(5,5);
test_a = test_a - text_b;
std::cout << test_a.a <<std::endl;
std::cout << test_a.b <<std::endl;
return 0;
}
运行结果:
3
4
- [] 运算符重载
#include
class my_vertor{
public:
my_vertor(){};
~my_vertor(){};
int str[8] = {1,2,3,4,5,6,7,8};
int operator [] (int x);
int num;
};
int my_vertor::operator [](int x){
return str[x];
}
int main(){
my_vertor m_ver;
std::cout<< m_ver[2] <<std::endl;
return 0;
}
运行结果:
3
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)