【问题标题】:Inheritance and constructors in c++C++中的继承和构造函数
【发布时间】:2018-06-28 04:05:35
【问题描述】:

如何在子类构造函数中调用超类构造函数?以下代码不起作用,缺少什么?我很迷惑。提前感谢您的帮助:)

#include <iostream>
#include<string>
using namespace std;

class Carre{
public:
    Carre(){}
    Carre(string nom){_nom=nom;}
    string getNom(){return _nom;}

protected:

    string _nom;

};

class Propriete : public Carre
{
public:
    Propriete(){}

    Propriete(string nom,const int prix):Carre(nom),_prix(prix){}
    int get_prix(){return _prix;}

protected:
    int _prix;

};

class Terrain : public Propriete
{
public:
    Terrain(){};
    Terrain(string nom,const int prix, const int loyer){
        Propriete(nom,prix);
        _loyer = loyer;}
    protected :
    int _loyer;

};


int main(int argc, const char * argv[]) {

    Terrain * T1 = new Terrain("T1", 6000, 120);
    cout << T1->getNom()<<" and "<<T1->get_prix() <<endl;

    delete T1;

    return 0;
}

提前感谢您的帮助:)

【问题讨论】:

  • 提示:你已经知道答案了,因为你在Propriete!
  • 请比“不起作用”更具体。
  • 关于公认命名法的注释 - 在 C++ 中,我们说的是“基类”和“派生”类,也不是“超类”和“子类”。
  • 啊,但是在人类为无阶级社会而奋斗的日子里……

标签: c++ inheritance constructor superclass


【解决方案1】:
class Base
{
    protected:
        string s;

    public:
        Base(string s)
        : s(s) // Initialize member variable s from parameter s
        {
            // Do stuff
        }
};

class Derived : public Base
{
    protected:
        int i;

    public:
        Derived(string s, int i)
        : Base(s), // Call base class constructor
          i(i)     // Initialize member variable i from parameter i
        {
            // Do stuff
        }

};

【讨论】:

  • 这种情况下不需要显式调用基础构造函数。
猜你喜欢
  • 2012-11-14
  • 2017-08-09
  • 2015-07-09
  • 2013-12-24
  • 2018-11-06
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
相关资源
最近更新 更多