有两个班级。一个是从基类派生的。这两个类都有参数化的构造函数。
#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] 删除。
我来说两句