读书人

重载解引用操作符的有关问题

发布时间: 2013-08-25 10:49:56 作者: rapoo

重载解引用操作符的问题
下面是侯捷的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.就是代码中的注释部分。
2.两个重载的++操作符,要想调用那个带参数的,是不是只能t.operator++(0);这样调用? c++ ?解引用操作符 自增自减操作符
[解决办法]
int& operator*() const{
return (int&)m_i;
//以上转换操作告诉编译器,你确实要将const int转换为non-const lvalue
//不知道这句话什么意思??????m_i也不是const啊。
}
--------------------
函数后面的const表示 const *this ,所以 this->m_i也是const的
把函数括号后的const去掉就行。

operator++() // 前++ 比如t是类的对象 ++t
operator++(int i) //后++ 比如 t++
[解决办法]

1
int& operator*() const{ // 这个const 的作用引起的!
//个“只读”函数,它既不能更改数据成员的值,
//也不能调用那些能引起数据成员值变化的成员函数,只能调用const成员函数
return (int&)m_i;
}

2 定类是一个新的类型,你在作加法减法操作的时候,编译器不知道如何操作,所有得重载, 用法和普通的加法一样的

INT A(5) ;
INT B(10);
INT C = A + B;

读书人网 >C++

热点推荐