c ++子类不能初始化Base类的成员变量? [英] c++ Child class Unable to initialize Base class's member variable?

查看:222
本文介绍了c ++子类不能初始化Base类的成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这个问题添加到我以前的关于在初始化列表中初始化成员向量的问题。



这里是我的基础&派生类定义...

  class Base {
public:
std :: vector< int& m_Vector;
}


类派生:public Base {
Derived():m_Vector {1,2,3} {} //引用m_Vector时出错
}

当试图初始化Derived的m_Vector ..我在Visual Studio中得到一个错误, / p>

 m_Vector不是类Derived的非静态数据成员或基类



为什么派生类在这种情况下不能引用m_Vector?

解决方案

在初始化之后,您可以在派生类构造函数中修改数据成员,但是您需要在基类中执行初始化。例如,

  class Base 
{
public:
std :: vector< int> ; m_Vector;
Base():m_Vector {1,2,3} {}
};

类派生:public Base
{

};

这是因为基类(及其扩展名,其所有数据成员)类和其任何成员。



如果您需要能够控制 Base 的初始化值来自 Derived 的数据成员,可以向 Base 添加合适的构造函数,并在派生

  class Base 
{
public:
std :: vector< int> m_Vector;
Base(const std :: vector< int>& v):m_Vector(v){}
Base(std :: vector< int>& v):m_Vector move(v)){}
};

class Derived:public Base
{
public:
Derived():Base({1,2,3}){}

};


So this question adds to my previous question about initializing member vector in an initialization list..

Here are my base & derived class definitions...

class Base {
public:
    std::vector<int> m_Vector;
}


class Derived : public Base {
    Derived() : m_Vector {1, 2, 3} {}      // ERROR when referring to m_Vector
}

When trying to initialize Derived's m_Vector.. I get an error in Visual Studio saying that

"m_Vector" is not a nonstatic data member or base class of class "Derived"

Why can't derived class refer to m_Vector in this case..?

解决方案

You can modify the data member in the derived class constructor after it has been initialized, but you need to perform the initialization in the base class. For example,

class Base 
{
public:
    std::vector<int> m_Vector;
    Base() : m_Vector {1, 2, 3} {} 
};

class Derived : public Base 
{

};

This is because the base class (and by extension, all its data members) are initialized before the derived class and any of its members.

If you need to be able to control the initialization values of Base's data members from Derived, you can add a suitable constructor to Base, and use this in Derived:

class Base 
{
public:
    std::vector<int> m_Vector;
    Base(const std::vector<int>& v) : m_Vector(v) {}
    Base(std::vector<int>&& v) : m_Vector(std::move(v)) {}
};

class Derived : public Base 
{
public:
  Derived() : Base({1, 2, 3}) {}

};

这篇关于c ++子类不能初始化Base类的成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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