【发布时间】:2021-08-29 13:07:21
【问题描述】:
有两个类。一个是从基类派生的。这两个类都有参数化的构造函数。
#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;
}
在上面的代码中,当我创建子类的对象时,值 10 将传递给两个构造函数。我想知道有没有一种方法可以重新编码上面的代码,我可以传递不同的值 每当我创建一个子对象并将一个值传递给它的构造函数时,就传递给基类构造函数。 例如:- 我将创建一个子对象并将值 20 传递给它的构造函数,但我想将用户输入的值传递给基类构造函数,以便 int a 和 int b 具有不同的值(我假设基类每当我创建子构造函数时都会隐式调用构造函数) 谢谢!!
【问题讨论】:
-
根据
child::child(int x, int y):parent(x), b(y)可能有什么?!?我可能不明白你的问题...... -
为了避免大量输入:在
parent成员函数中使用时,不要使用parent::a,而只需说a。构造函数:parent::parent(int x) : a(x) {}
标签: c++ oop inheritance constructor