C++运算符重载范例

来源:互联网 发布:windos系统mac怎么 编辑:程序博客网 时间:2024/06/03 18:02
#include <iostream>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*
int main(int argc, char** argv) {
return 0;
}
*/ 
#if 1 //友元函数重载运算符  复数加法 
class complex{
private:
float x;
float i;
public:
complex(int a=0,int b=0){
this->x=a;
this->i=b; 
}
void show(){
std::cout << " = " << x << " + " << i << "i" << std::endl; 
}
friend complex operator++(complex &c1);
friend complex operator++(complex &c1,int);
friend complex operator+(float,complex);
}; 
complex operator++(complex &c1){ // ++complex
std::cout << "++complex" << std::endl;
c1.x++;
c1.i++;
return c1;

complex operator++(complex &c1,int){ //complex++
std::cout << "complex++" << std::endl;
complex c2(c1.x++,c1.i++);
return c2;
}
complex operator+(float f,complex c1){
complex c2;
c2.x=c1.x+f;
c2.i=c1.i;
return c2;
}
int main(int argc, char** argv) {
class complex c1(12,3),c2;

c1.show();

c2 = ++c1;

c2.show();
c1.show();

c2 = 2.2 + c1;
c2.show();
c1.show();

return 0;
}
#endif


#if 0 //成员函数重载运算符  复数加1 
class complex{
private:
int x;
int i;
public:
complex(int a=0,int b=0){
this->x=a;
this->i=b; 
}
void show(){
std::cout << " = " << x << " + " << i << "i" << std::endl; 
}
complex operator++(){   // ++complex
std::cout << "++complex" << std::endl;
x++;
i++;
return *this;
}
complex operator++(int){ //complex++
std::cout << "complex++" << std::endl;
complex c1(x++,i++);
return c1;
}
}; 
int main(int argc, char** argv) {
class complex c1(12,3),c2;

c1.show();

c2 = ++c1;

c2.show();
c1.show();

return 0;
}
#endif








#if 0 //成员函数重载运算符号 
class X{
private:
int x;
public:
X(int x);
X(){return;}
X operator+(X obj);//成员函数重载运算符原型 
void show(){
std::cout << x << std::endl; 

};


X::X(int x)
{this->x = x;}
X X::operator+(X obj){
class X tmp;
tmp.x = obj.x+x;
return tmp; 

int main(int argc, char** argv) {
class X x1(12),x2(23),c;
c = x1+x2;
c.show();
return 0;
}
#endif
原创粉丝点击