简体   繁体   English

C++ 派生类仅使用继承的基构造函数的一部分

[英]C++ Derived classes only using part of inherited base constructor

I am certain that this is a basic question but I have not been able to find the answer anywhere.我确信这是一个基本问题,但我无法在任何地方找到答案。 Let's say I have a base class with constructor:假设我有一个带有构造函数的基础 class :

class Parent{
public:
    double propertyA, propertyB;
    Parent(double propertyA, double propertyB){
        this->propertyA = propertyA;
        this->propertyB = propertyB;
}
};

and then I want a derived class to use this base constructor but it will only need to take in propertyB .然后我想要一个派生的 class 来使用这个基本构造函数,但它只需要接受propertyB propertyA will end up being a constant (let's say 1.0 ). propertyA最终将成为一个常数(比如说1.0 )。

Currently I am trying:目前我正在尝试:

class Child : public Parent {
public:
    Child(double PropertyB): Parent(1.0, PropertyB) {}
};

I am not certain that this behaves as I want it to though.我不确定这是否符合我的要求。 Is this how I should be doing this?这是我应该这样做的吗?

The only way to be sure is to test, I think:唯一可以确定的方法是测试,我认为:

#include <iostream>

class Parent
{
public:
    double propertyA, propertyB;
    Parent(double propertyA, double propertyB)
    {
        this->propertyA = propertyA;
        this->propertyB = propertyB;
    }
};
class Child : public Parent
{
public:
    Child(double PropertyB): Parent(1.0, PropertyB) {}
    double getPropertyA()
    {
        return propertyA;
    }
    double getPropertyB()
    {
        return propertyB;
    }
};

int main()
{
    double a = 3.0;
    double b = 5.0;
    Parent* parent = new Parent(a,b);
    Child* child = new Child(b);
    std::cout << "PropertyA for child " << child->getPropertyA();
}

The output is: output 是:

1 

You can simply overload the constructor.您可以简单地重载构造函数。 Code should be like this -代码应该是这样的 -

class Parent{
public:
    double propertyA, propertyB;
    Parent(double propertyA, double propertyB){
        this->propertyA = propertyA;
        this->propertyB = propertyB;
    }
    Parent(double propertyB){ 
        this->propertyA = 1.0; // constant value
        this->propertyB = propertyB;
    }
};
class Child : public Parent {
public:
    Child(double PropertyB): Parent(PropertyB) {

    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM