const引用必须在构造函数base /成员初始化器列表中初始化 [英] const reference must be initialized in constructor base/member initializer list

查看:152
本文介绍了const引用必须在构造函数base /成员初始化器列表中初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图阻止访问我写的类的默认构造函数。我想让别人使用的构造函数需要一个const引用另一个对象。我已经使默认构造函数私有,以防止其他人使用它。我得到一个编译器错误的默认构造函数,因为const引用成员变量未正确初始化。我可以做什么来做这个编译?

  class CFoo 
{
public:
CFoo();
〜CFoo();
};

class CBar
{
public:
CBar(const CFoo& foo):fooReference(foo)
{
} $ b b
〜CBar();

private:
const CFoo& fooReference;

CBar()//我得到一个编译器错误,因为我不知道该怎么做fooReference这里...
{
}
};


解决方案

不要声明默认构造函数。

  class CBar 

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


相当全面的解释构造函数可以在这里找到:
http://www.parashift.com/c++-faq-lite/ctors.html


I am trying to block access to the default constructor of a class I am writing. The constructor I want others to use requires a const reference to another object. I have made the default constructor private to prevent others from using it. I am getting a compiler error for the default constructor because the const reference member variable is not initialized properly. What can I do to make this compile?

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...
    {
    }
};

解决方案

don`t declare default constructor. It is not available anyway (automatically that it's) if you declare your own constructor.

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

fairly comprehensive explanation of constructors can be found here: http://www.parashift.com/c++-faq-lite/ctors.html

这篇关于const引用必须在构造函数base /成员初始化器列表中初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆