c++ - 将子变量传递给父构造函数

标签 c++ class constructor

我正在尝试将一个变量从父类传递到它的子类。 代码确实可以编译,但一直给我结果; 0。 当我在子类的基类构造函数中硬编码值时,它确实给了我想要的结果。

父类.h:

class Parent{
 float price;

public:
 Parent(float price)
}

父类.cpp:

 #include "Parent.h"

 Parent::Parent(float price){
 this->price = price;
 }

子类.h:

 class Child : Parent{
 const float price = 0.29;

 public:
 Child();
 }

子类.cpp:

#include "Child.h"

Child::Child() : Parent(price){
}

如何才能让子类中的var可以在基类的构造函数中使用?

最佳答案

请注意 initialization order是:

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

...

  • 2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

  • 3) Then, non-static data members are initialized in order of declaration in the class definition.

...

基础子对象总是在数据成员之前被初始化;这意味着当您尝试将数据成员 Child::price 传递给基类 Parent 的构造函数时,它尚未初始化。

关于c++ - 将子变量传递给父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57943552/

相关文章:

c++ - 来自同一个原始指针的两个 std::shared_ptr

JavaScript:这个构造函数有什么问题?

c++ - 3D 立方体绘图,只有一侧始终在最上面

ruby - Ruby 中的模块和类。矛盾?

ios - SKEmitterNode的自定义类子类不起作用

ios - 如何让我的 Swift 类实时更新 View Controller 中的标签?

C# 继承构造函数子和父 ??

C++在小例子中不能直接调用构造函数

c++ - 使用 c++/openssl 解密带有密码的文件

c++ - 在 Visual Studio C++ 中访问程序数据库时出错