前置运算符重载为一元运算符,后置运算符重载为二元运算符。
Operator int() { return n; }
int作为一个强制类型转换运算符被重载,
Demo s;
(int)s; //等效于s.int();
强制类型转换运算符重载时,
运算符重载的注意事项
#include <iostream> using namespace std; class Ctype { private: int n; public: Ctype(int m) :n(m) {}; Ctype operator ++(int); Ctype operator ++(); operator int(); }; Ctype Ctype::operator++(int) { Ctype tmp(*this); n++; return (tmp); } Ctype Ctype::operator++() { n++; return (*this); } Ctype::operator int() { return n; } int main() { Ctype c(6); cout << c++ << endl; cout << c << endl; cout << ++c << endl; return 0; }
原文:http://www.cnblogs.com/helloforworld/p/5655272.html