重载解引用操作符的问题
下面是侯捷的STL源码剖析中的一个小程序。对于其中的一个注释不理解。
#include <iostream>
using namespace std;
class INT {
friend const ostream& operator<<(ostream&, const INT&);
public:
INT(int i):m_i(i) {}
INT& operator++() {
++(this->m_i);
return *this;
}
const INT& operator++(int i) {
INT tmp = *this;
++(*this);
return tmp;
}
INT& operator--() {
--(this->m_i);
return *this;
}
const INT& operator--(int i) {
INT tmp = *this;
--(*this);
return tmp;
}
int& operator*() const{
return (int&)m_i;
//以上转换操作告诉编译器,你确实要将const int转换为non-const lvalue
//不知道这句话什么意思??????m_i也不是const啊。
}
private:
int m_i;
};
const ostream& operator<<(ostream& os, const INT& t) {
os << "[" << t.m_i << "]" << endl;
return os;
}
int main()
{
INT t(5);
cout << ++t;
cout << t.operator++(0);
cout << t;
cout << *t;
return 0;
}
1
int& operator*() const{ // 这个const 的作用引起的!
//个“只读”函数,它既不能更改数据成员的值,
//也不能调用那些能引起数据成员值变化的成员函数,只能调用const成员函数
return (int&)m_i;
}
2 定类是一个新的类型,你在作加法减法操作的时候,编译器不知道如何操作,所有得重载, 用法和普通的加法一样的
INT A(5) ;
INT B(10);
INT C = A + B;