代码之家  ›  专栏  ›  技术社区  ›  Trevor Balcom

常量引用必须在构造函数基/成员初始值设定项列表中初始化

  •  9
  • Trevor Balcom  · 技术社区  · 14 年前

    class CFoo
    {
    public:
        CFoo();
        ~CFoo();
    };
    
    class CBar
    {
    public:
        CBar(const CFoo& foo) : fooReference(foo)
        {
        }
    
        ~CBar();
    
    private:
        const CFoo& fooReference;
    
        CBar() // I am getting a compiler error because I don't know what to do with fooReference here...
        {
        }
    };
    
    2 回复  |  直到 14 年前
        1
  •  13
  •   Anycorn    14 年前

    不要声明默认构造函数。 如果您声明自己的构造函数,那么它无论如何都不可用(自动地,它是)。

    class CBar
    {
    public:
        CBar(const CFoo& foo) : fooReference(foo)
        {
        }
    private:
        const CFoo& fooReference;
    };
    

    关于构造器的比较全面的解释可以在这里找到: http://www.parashift.com/c++-faq-lite/ctors.html

        2
  •  4
  •   jpalecek    14 年前

    class CBar
    {
    public:
        CBar(const CFoo& foo) : fooReference(foo)
        {
        }
    
        ~CBar();
    
    private:
        const CFoo& fooReference;
    
        CBar();
    };
    

    在这种情况下,这可能有点多余,因为编译器不会为具有引用成员的类创建默认构造函数,但最好将其放在那里,以防删除引用成员。