
在C++中,自定义类时,需要重载一些特定的操作符,让自定义类具有跟基本数据类型一致的运算符操作。
- 自定义类的基本模型
- 类内部重载
- 类外部重载
- 不同点和原因
用模板类更加直观的发现问题的所在。
1 2 3 4 5 6 7 8 9 10 11 12 13
|
template<class > class Table{ public: Table(); T getData(); ~Table();
private: T width; T height; T length; };
|
类内部重载
在类内部添加输入输出流操作符重载时,需要添加友元friend
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
template<class > class Table{ public: Table(); T getData(); ~Table();
friend std::ostream& operator<<(std::ostream& os, Table<T>& t) { return os << t.width << " " << t.height << " " << t.length; }
private: T width; T height; T length; };
|
类外部重载
类外部重载时,不需要添加友元,但需要声明为模板函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
template<class > class Table{ public: Table(); T getData(); ~Table();
private: T width; T height; T length; }
template<class > std::ostream& operator<<(std::ostream& os, Table<T>& t) { return os << t.getData(); }
|
不同点和原因
在类内部定义时,需要添加为友元,类才能去识别该重载函数是内部成员函数。
在类外部定义时,可以抛开友元属性,取而代之的是函数模板声明,毕竟类不能识别为它内部成员函数。在类外定义的重载函数是不能调用内部private成员的,要在类内部定义公共调用接口。
近期评论