【问题标题】:I can't call constructor of inner class with this pointer of outer class我不能用这个外部类的指针调用内部类的构造函数
【发布时间】:2019-06-25 12:50:23
【问题描述】:

我不知道为什么下面的代码编译失败并出现错误:

"没有构造函数实例 "cb::iterator::iterator" 匹配 参数列表参数类型为:(int, const cb)"

但是当我取消注释第二个版本的构造函数时,代码编译得很好! 为什么编译器将*this 视为常量?

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);

}

【问题讨论】:

    标签: inner-classes this-pointer const-method


    【解决方案1】:

    对于class X,如果X 的成员函数声明为const,则this 指针的类型为X* const。所以在这种情况下构造函数的参数也应该是const

    这里有完整的解释:
    'this' pointer in C++

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      相关资源
      最近更新 更多