简体   繁体   English

我不能用外部类的指针来调用内部类的构造函数

[英]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.

相关问题 我们可以在外部类的构造函数中创建内部类的对象吗? - Can we create an object of the inner class in the constructor of the outer class? 为什么嵌套类时不能从内部 class 访问外部 class 的私有成员? - Why can't I access private members of the outer class from the inner class when nesting classes? 通过外部 class 调用内部 class 的方式 - Way to call inner class by outer class 如何在外部 class 中调用内部 class 的 function? - How to call a function of inner class in outer class? 外部类可以访问内部类的成员吗? - Can an outer class access the members of inner class? 为什么在内部 class 构造函数中没有外部 class object 的 LocalVariableTable 条目(Java 字节码) - Why isn't there an entry in LocalVariableTable for outer class object in an inner class constructor(Java Bytecode) 内部类对象进入外部类构造函数进入c# - Inner class object into Outer class constructor into c# 在外部类的构造函数中实例化内部类是否危险? (JAVA) - Is it dangerous to instantiate an inner class within the outer class's constructor? (Java) Java - 内部类构造函数 - 仅允许外部类 - Java - Inner class constructor - allowed for outer class only 从外部类非静态构造函数访问内部类的静态方法 - Accessing static methods of inner class from an outer class nonstatic constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM