我不知道为什么下面的代码无法编译并出现错误:
“没有构造函数“cb::iterator::iterator”的实例与 参数列表参数类型为:(int, const cb)"
但是当我取消注释第二个版本的构造函数时,代码可以正常编译! 为什么编译器将
*this
视为 const?
class cb
{
public:
class iterator
{
public:
iterator(int x, cb& c):cb_(c) { x_ = x; }
//iterator(int x, const cb& c) :cb_(c) { x_ = x; }
private:
int x_;
//cb a;
const cb& cb_;
};
iterator begin() const;
};
cb::iterator cb::begin() const
{
return iterator(1, *this);
}
对于
class X
,如果 X 的成员函数声明为 this
,则 X* const
指针的类型为 const
。所以这种情况下构造函数的参数也应该是const
。
这是完整的解释:
C++ 中的“this”指针