派生类的初始化程序列表 [英] Initializer List for Derived Class

查看:212
本文介绍了派生类的初始化程序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个派生类,该类具有一个默认构造函数,用于初始化受感染的成员.

I want to have a derived class which has a default constructor that initializes the inheirited members.

我为什么可以这样做

class base{
protected:
 int data;
};

class derived: public base{
public:
 derived(){ //note
  data = 42;
 }
};

int main(){
 derived d();
}

但不是这个

class base{
protected:
 int data;
};

class derived: public base{
public:
 derived(): //note
  data(42){}
};

int main(){
 derived d();
}

error: class ‘derived’ does not have any field named ‘data’

推荐答案

一个对象只能初始化一次. (唯一的例外是,先将其初始化然后销毁;然后可以稍后再次对其进行初始化.)

An object can only be initialized once. (The exception is if you initialize it and then destroy it; then you can initialize it again later.)

如果您可以做您想做的事,那么base::data可能会被初始化两次. base的某些构造函数可能会对其进行初始化(尽管在您的特殊情况下不会),然后derived构造函数可能会对其进行初始化.为了防止这种情况,该语言仅允许构造函数初始化其自己的类的成员.

If you could do what you're trying to do, then base::data could potentially be initialized twice. Some constructor of base might initialize it (although in your particular case it doesn't) and then the derived constructor would be initializing it, potentially for a second time. To prevent this, the language only allows a constructor to initialize its own class's members.

初始化不同于赋值.分配给data没问题:您只能初始化data一次,但可以根据需要分配多次.

Initialization is distinct from assignment. Assigning to data is no problem: you can only initialize data once but you can assign to it as many times as you want.

您可能想为base编写一个构造函数,并使用data的值.

You might want to write a constructor for base that takes a value for data.

class base{
protected:
 int data;
 base(int data): data(data) {}
};

class derived: public base{
public:
 derived(): base(42) {}
};

int main(){
 derived d{}; // note: use curly braces to avoid declaring a function
}

这篇关于派生类的初始化程序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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