c/c++ 友元的简单应用
程序员文章站
2022-03-18 15:36:59
友元的简单应用 1,对象 + 对象,或者,对象 + 数字,可以用类的成员函数去重载+号函数,但是,数字 + 对象就不能用类的成员函数去重载+号函数了, 因为编译器会把数字 + 对象翻译成数字.operator+(const 类 &对象),因为数字不是类的对象,无法传递给类的成员函数this指针。 用 ......
友元的简单应用
1,对象 + 对象,或者,对象 + 数字,可以用类的成员函数去重载+号函数,但是,数字 + 对象就不能用类的成员函数去重载+号函数了,
因为编译器会把数字 + 对象翻译成数字.operator+(const 类 &对象),因为数字不是类的对象,无法传递给类的成员函数this指针。
用友元去重载:数字 + 对象
2,用友元去重载:>>运算符和<<运算符。
其实用类的成员函数也可以重载<<运算符,但是使用起来比较怪异,不能使用cout << 对象,只能使用对象 << cout。
#include <iostream> using namespace std; class imaginary{ friend imaginary operator+(int i, const imaginary &m); friend ostream& operator<<(ostream &os, const imaginary &m); friend istream& operator>>(istream &is, imaginary &m); public: imaginary():real(0), imag(0){ cout << "c:" << this << endl; } imaginary(int real, int imag):real(real), imag(imag){ cout << "c:" << this << endl; } imaginary operator+ (const imaginary &m){ return imaginary (real + m.real, imag + m.imag); } imaginary operator+ (int i){ return imaginary(real + i, imag); } imaginary& operator= (const imaginary &m){ cout << "asign" << endl; if(this != &m){ real = m.real; imag = m.imag; } return *this; } ostream& operator<<(ostream& os){ os << "[" << real << "," << imag << "]"; return os; } ~imaginary(){ cout << this << endl; } private: int real; int imag; }; imaginary operator+(int i, const imaginary &m){ return imaginary(i + m.real, m.imag); } ostream& operator<<(ostream &os, const imaginary &m){ os << "(" << m.real << "," << m.imag << ")"; return os; } istream& operator>>(istream &is, imaginary &m){ is >> m.real >> m.imag; return is; } int main(){ imaginary m1(10, 20); imaginary m2(1, 2); imaginary m3 = m1 + m2; imaginary m4 = m1 + 10; imaginary m5 = 20 + m1; cout << "a" << m5 << "aa" << endl;; m5 << cout << "bb" << endl; imaginary m6; cin >> m6; cout << m6 << endl; return 0; }