C ++ 11类的继承

时间:2017-03-16 22:08:28

标签: c++ c++11 inheritance

#include <string>
#include <iostream>
using namespace std;
class Surgery
{
public:
    Surgery();
    int getPrice();
    string getType();
protected:
    int price;
    string type;
};

Surgery::Surgery()
{
    price = 0;
    type = "";
}

int Surgery::getPrice()
{
    return price;
}

string Surgery::getType()
{
    return type;
}

class Neurosurgery :public Surgery
{
private:
    string type = "Neurosurgery";
    int price = 23000;
};
class Plastic :public Surgery
{
private:
    string type = "Plastic";
    int price = 15000;
};
class Trauma :public Surgery
{
private:
    string type = "Trauma";
    int price = 5000;
};
class Endocrine :public Surgery
{
private:
    string type = "Endocrine";
    int price = 20000;
};
class Ophthalmological :public Surgery
{
public:
    Ophthalmological();
private:
    string type;
    int price;
};

Ophthalmological::Ophthalmological():Surgery()
{
    type = "Ophthalmological";
    price = 10000;
}

int main()
{
    Ophthalmological var1;
    cout << var1.getPrice() << endl;
    return 0;
}

当我运行此代码时,我希望看到10000 相反,我看到0

我使用const,singlone默认构造函数避免任何错误变得非常简单。

First Surgery构造函数在神经外科手术后执行。

Neurosurgery构造函数应该覆盖默认的Surgery构造函数所做的值。

我是否使用错误风格的c ++ 11

2 个答案:

答案 0 :(得分:1)

这是因为它不是虚拟的,并且有多个具有相同名称的变量。所以你从基类手术中获得价值。其他类也定义具有相同名称的变量。我认为最简单的解决方案是:将受保护的变量保存在基类中,并从子类中删除这些变量。

答案 1 :(得分:1)

这是因为您声明可变价格和类型的两倍,并且当您调用cout << var1.getPrice() << endl;时,它采用变量Surgery。你应该这样做:

class Surgery
{
public:
    Surgery();
    int getPrice();
    string getType();
protected:
    int price;
    string type;
};

class Ophthalmological :public Surgery
{
public:
    Ophthalmological();
private:
    //string type; //It has been declared into Survey
    //int price;   //It has been declared into Survey
}; 

我使用此修改运行您的代码并返回唯一price变量的值。