![](/img/trans.png)
[英]Can we create an object of the inner class in the constructor of the outer class?
[英]I can't call constructor of inner class with this pointer of outer class
我不知道为什么下面的代码无法编译并显示错误:
“没有构造函数实例” 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的成员函数声明为const
,则this
指针的类型为X* const
const
。 因此,在这种情况下,构造函数的参数也应为const
。
这里是完整的解释:
C ++中的“ this”指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.