C++的大多数运算符都可以通过operator来实现重载。
简单的operator+
#include <iostream> using namespace std; class A { public: A(int x){i=x;} int i; A &operator+(A &p) { this->i+=p.i; return *this; } }; void main() { A a(10),b(20),c(0); c=a+b; cout<<c.i<<endl; system("pause"); }
简单的operator++
#include <iostream> using namespace std; class A { public: A(int x){i=x;} int i; A &operator++() { this->i++; return *this; } }; void main() { A a(10); a++; cout<<a.i<<endl; system("pause"); }
深层operator=
#include <iostream> using namespace std; class A { public: A(int x){i=new int;*i=x;} ~A(){delete i;i=0;} A(const A&p) { i=new int; *i=*(p.i); } int *i; A &operator=(A &p) { *i=*(p.i); return *this; } int pp(){return *i;} }; void main() { A a(10),b(0); a=b; cout<<a.pp()<<endl; system("pause"); }
时间: 2024-10-11 04:58:41