[英]I can't call constructor of inner class with this pointer of outer class
I don't know why below code failed to compile with error: 我不知道为什么下面的代码无法编译并显示错误:
"no instance of constructor "cb::iterator::iterator" matches the argument list argument types are:(int, const cb)"
“没有构造函数实例” cb :: iterator :: iterator“匹配参数列表参数类型为:(int,const cb)”
But the code compiles fine when i uncomment the second version of constructor! 但是,当我取消注释构造函数的第二个版本时,代码编译良好! why compiler considers
*this
as const? 为什么编译器将
*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);
}
For a class X
, the type of this
pointer is X* const
if a member function of X is declared as const
. 对于
class X
,如果将X的成员函数声明为const
,则this
指针的类型为X* const
const
。 So the parameter of constructor in this case should to be const
too. 因此,在这种情况下,构造函数的参数也应为
const
。
Here is a full explanation: 这里是完整的解释:
'this' pointer in C++ C ++中的“ this”指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.