有元函数简单学习
1. C++类私有部分访问的方法:类公有方法、有元(有元函数、友元类和有元成员函数)。
2. 运算符重载
class Test{...};
Test t, t1, t2;
// --------------- 两个类对象的 + - * / % 等的运算符重载 -------------
t = t1 + t2; // t = t1.operator+(t2); 原型为:
Test operator+(const Test &t); <=>Test operator+(const Test *this, const Test &t);
t = t1*t2; // t = t1.operator*t2;
// ------------------- 类对象和“非对象”的预算符重载-----------------
t = t1*10; // t = t1.operator*(10); 左侧的操作数为调用对象,运算符重载的是成员函数--->原型为 Time operator*(const);
t = 10*t1; // 左侧操作数为非对象怎么办???可采用非成员函数--->原型为 Time operator*(int i, const Test &t);
于是:t = operator*(10, t1);
B U T 非成员函数不能调用私有数据,但friend函数可以----->friend Time operator*(int i, const Test &t);
但是int i 可能不需要访问私有数据!看下面输出运算符重载:
ostream& operator<<(ostream & out, const Test &t);
其中,out为类输出流out对象,但还不是Test类对象,因此还不能直接访问Test类私有部分,怎么解决?
--->声明为有元函数:friend ostream& operator<<(ostream & out, const Test &t);
另外,输入运算符重载类似!
3. 重载运算符: 作为成员函数还是非成员函数
Notes:① 非成员函数应该为有元函数,这样才能直接访问类的私有数据,原型比如:
Test operator+(const Test &t) const; // 成员版本 <=> Test operator+(const Test *this, const Test &t);
一个操作数通过this指针隐式传递。
friend Test operator+(const Test &t1, const Test &t2) const; // 非成员版本,有元函数,无this指针,操作数显示标出。
② 使用有元函数,须现在类内声明。