C++派生类的参数化构造函数

时间:2021-06-13 08:53:59

标签: c++ oop inheritance constructor

有两个类。一个是从基类派生的。这两个类都有参数化的构造函数。

#include<string>
#include<iomanip>

//declaring parent class
class parent
{
protected:
    int a;
public:
    parent(int x);
    void displayx();
};

//declaring child class
class child:public parent
{
private:
    int b;
public:
    child(int y);
    void displayy();
};

//defining constructors and methods of parent class
parent::parent(int x)
{
    parent::a=x;
    std::cout<<"parent \n";

}
void parent::displayx()
{
    std::cout<<parent::a<<"\n";
}

//defining constructors and methods of child class
child::child(int y):parent(y)
{
    child::b=y;
    std::cout<<"child \n";
}

void child::displayy()
{
    std::cout<<child::b;
}

//main function
int main()
{
    child c1(10);// creating a child object
    //displaying values of int a and int b
    c1.displayx();
    c1.displayy();
    return 0;
}





在上面的代码中,当我创建类 child 的对象时,值 10 将被传递给两个构造函数。我想知道有没有一种方法可以重新编码上面的代码,以便我可以传递不同的值 每当我创建一个子对象并将一个值传递给它的构造函数时,都会传递给基类构造函数。 例如:- 我将创建一个子对象并将值 20 传递给它的构造函数,但我想将用户输入的值传递给基类构造函数,以便 int a 和 int b 将具有不同的值(我假设基类每当我创建子构造函数时都会隐式调用构造函数) 谢谢!!

1 个答案:

答案 0 :(得分:3)

您的 child 类的构造函数可以采用两个值 - 一个用于 a,一个用于 b,您可以将第一个值传递给父构造函数:

class child : public parent
{
// ...
public:
    child(int x, int y);
// ...
};


child::child(int x, int y) : parent(x)
{
    b = y;
    std::cout << "child \n";
}

int main()
{
    child c1(20, 10);// creating a child object
    // ...
}

我还认为您打算包含 <iostream> 而不是 <iomanip>

相关问题