【问题标题】:Parameterized constructors of derived class in C++C++派生类的参数化构造函数
【发布时间】: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


【解决方案1】:

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
    // ...
}

另外,我认为您的意思是包含 &lt;iostream&gt; 而不是 &lt;iomanip&gt;

【讨论】:

  • 更好: parent(x), b(y) {...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 2023-04-07
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2015-08-18
  • 2018-07-11
相关资源
最近更新 更多