#include <iostream> using namespace std; class Integer { long i; Integer* This() { return this; } public: Integer(long ll = 0) : i(ll) {} // No side effects takes const& argument: friend const Integer& operator+(const Integer& a); friend const Integer operator-(const Integer& a); friend const Integer operator~(const Integer& a); friend Integer* operator&(Integer& a); friend int operator!(const Integer& a); // Side effects have non-const& argument: // Prefix: friend const Integer& operator++(Integer& a); // Postfix: friend const Integer operator++(Integer& a, int); // Prefix: friend const Integer& operator--(Integer& a); // Postfix: friend const Integer operator--(Integer& a, int); }; // Global operators: const Integer& operator+(const Integer& a) { cout << "+Integer\n"; return a; // Unary + has no effect } const Integer operator-(const Integer& a) { cout << "-Integer\n"; return Integer(-a.i); } const Integer operator~(const Integer& a) { cout << "~Integer\n"; return Integer(~a.i); } Integer* operator&(Integer& a) { cout << "&Integer\n"; return a.This(); // &a is recursive! } int operator!(const Integer& a) { cout << "!Integer\n"; return !a.i; } // Prefix; return incremented value const Integer& operator++(Integer& a) { cout << "++Integer\n"; a.i++; return a; } // Postfix; return the value before increment: const Integer operator++(Integer& a, int) { cout << "Integer++\n"; Integer before(a.i); a.i++; return before; } // Prefix; return decremented value const Integer& operator--(Integer& a) { cout << "--Integer\n"; a.i--; return a; } // Postfix; return the value before decrement: const Integer operator--(Integer& a, int) { cout << "Integer--\n"; Integer before(a.i); a.i--; return before; } int main() { Integer a; +a; -a; ~a; Integer* ip = &a; !a; ++a; a++; --a; a--; return 0; } ///:~
C++一元运算符重载
原创FrankNie0101 ©著作权
©著作权归作者所有:来自51CTO博客作者FrankNie0101的原创作品,谢绝转载,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
C++的拷贝构造和运算符重载
C++的拷贝构造和运算符重载
拷贝构造函数 运算符重载