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

谢汉查努卡

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

#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 将具有不同的值(我假设基类每当我创建子构造函数时都会隐式调用构造函数)谢谢!!

乔治

您的child的构造函数可以采用两个值 - 一个 fora和一个 for 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>.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C#根据参数类型实例化基础构造函数的派生类

C ++-派生类构造函数的行为

C ++基类构造函数,将派生类作为参数(?)

C++ 可以根据给单个构造函数的参数创建派生类而不是bass 类吗?

为什么派生类的构造函数要在C ++中初始化虚拟基类?

未调用派生类的c ++ / cli静态构造函数

C ++如何从具有一个参数的派生类构造函数调用具有两个参数的超类构造函数?

在派生类 C++ 的构造函数中调用基类的构造函数

C ++派生类构造函数调用基类构造函数错误

在C ++中初始化派生类参数

当派生类添加了数据成员时,派生类的构造函数应该如何像c ++中那样

C#-在派生类中调用基类和类构造函数

将派生类的成员函数指针作为参数传递时,选择了错误的C ++模板专业化

派生类是否可以具有不在C ++基类中的构造函数?

如何使用基类的数据成员作为派生类的构造函数?(在 C++ 中)

为C ++中的基类和派生类声明“虚拟”构造函数?

为什么派生类的构造函数只能在C ++的类中定义?

如何在C ++中从基类构造函数调用派生类方法?

创建基类对象使用派生类构造函数c ++

C ++将派生类的const值传递给基本意外行为的构造函数

多态C ++:基本指针字段未使用派生类构造函数提供的值

我是否必须为C ++中的派生类编写相同的构造函数?

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

C++ 派生类调用函数

C++ 继承:基类类型的虚函数中派生类类型的参数

如果只有C ++中的基类指针,则使用派生类参数重载函数

Cython / Python / C ++-继承:将派生类作为参数传递给需要基类的函数

派生类函数参数作为基类引用导致C2678

在 C++ 中使用模板调用派生类中父类的构造函数的正确语法是什么?