C++之重载操作符
1.类中重载+操作符
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class Object { public: Object() { } Object(int a) { num = a; } Object operator + (const Object& a) //重载+操作符; { Object result; result.num = num + a.num; return result; } private: int num; }; int main(int argc, char * argv[]) { int a = 10; int b = 20; Object obja(a); Object objb(b); Object objc = obja + objb; system("pause"); return 0; }
2.重载全局操作符
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class Object { friend Object operator + (const Object &a, const Object &b); public: Object() { } Object(int a) { num = a; } private: int num; }; Object operator + (const Object &a, const Object &b) { Object result; result.num = a.num + b.num; return result; } int main(int argc, char * argv[]) { Object obja(10); Object objb(20); Object objc = obja + objb; system("pause"); return 0; }
全局操作符,主要注意的是,当重载操作符访问私有成员时,需要将操作符声明为友元;
4. 重载[] 操作符
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class Object { public: Object() { } Object(char * str) { int size = strlen(str); m_buf = new char[size]; strcpy(m_buf,str); } char& operator [] (int index) { return m_buf[index]; } ~Object() { delete[] m_buf; } private: char *m_buf; }; int main(int argc, char * argv[]) { Object obja("weiyouqing"); char str = obja[0]; obja[0] = 'W'; system("pause"); return 0; }
5.重载==操作符
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class Object { public: Object() { } Object(int a) { num = a; } bool operator == (const Object &other) { if (num == other.num) return true; else return false; } ~Object() { } private: int num; }; int main(int argc, char * argv[]) { Object obja(2); Object objb(0); if (obja == objb) cout << "equal" << endl; else cout << "not equal" << endl; system("pause"); return 0; }
全局重载操作符:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class Object { friend bool operator == (const Object &a, const Object &b); public: Object() { } Object(int a) { num = a; } ~Object() { } private: int num; }; bool operator == (const Object &a,const Object &b) { if (a.num == b.num) return true; else return false; } int main(int argc, char * argv[]) { Object obja(2); Object objb(0); if (obja == objb) cout << "equal" << endl; else cout << "not equal" << endl; system("pause"); return 0; }
根据Effective C++中条款10.补充到:令赋值操作符返回一个reference to *this;
青青园中葵,朝露待日晞。
阳春布德泽,万物生光辉。
常恐秋节至,焜黄华叶衰。
百川东到海,何时复西归?
少壮不努力,老大徒伤悲!