C++ (Qt)class Number{ /* ... */public: virtual Number& operator +(Number& n) = 0; /* ... */} class PNumber : public Number{ /* ... */private: int acc;public: PNumber& operator +(Number& n); /* ... */}
C++ (Qt) virtual Number& Number::operator +(Number& n) = 0; ... PNumber& PNumber::operator +(Number& n);
C++ (Qt)Number& PNumber::operator +(Number& n){ PNumber * n2 = dynamic_cast <PNumber *> (n); if (!n2) assert(0); // складываем return *this;}
C++ (Qt)// обычная операция int a, b c; с = a + b; // теперь все то же но с классами friend PNumber operator + ( const PNumber & pn1, const PNumber & pn2 ); PNumber a, b c; с = a + b;
C++ (Qt)Nump *n = new PNumb();Nump *n1 = new PNumb();n = n + n1;
C++ (Qt)// базовый классclass Number { Number & operator += ( const Number & n1 ) // сам оператор не виртуальный { return DoVirtalInc(n1); // но вызывает виртуальный метод } virtual Number & DoVirtalInc( const Number & n1 ) = 0;}; // порожденный классclass PNumber { PNumber & operator += ( const PNumber & n1 ) // обычный не виртуальный оператор { acc += n1.acc; // складываем return *this; } virtual Number & DoVirtalInc( const Number & n1 ) { PNumber * pn1 = dynamic_cast <PNumber *> (&n1); if (pn1) *this += *pn1; return *this; }};
C++ (Qt)class TANumber{ ... virtual TANumber& operator + (TANumber& B) = 0;
C++ (Qt)class TReal : public TANumber{ ... virtual TReal& operator + (TANumber& B);};
C++ (Qt)class TReal : public TANumber{ ... virtual TNumber & operator + (TANumber& B);};
C++ (Qt)virtual bool operator == (TANumber& B);
C++ (Qt)virtual bool operator == (const TANumber& B) const;
C++ (Qt)class Number{public: Number() : _x(0) {} Number(int x) : _x(x) {} Number &operator+(const Number &x) { _x += x._x; return *this; } friend std::ostream& operator<<(std::ostream&, const Number&); //friend const Number operator+(const Number&, const Number&);private: int _x;}; std::ostream& operator<<(std::ostream& out, const Number& x) { out << x._x; return out;} /*const Number operator+(const Number&x1, const Number &x2) { return Number(x1._x + x2._x);}*/ Number n1 = 1;Number n2 = 2; Number n3 = n1+(1+n2); cout << n3 << endl;