【问题标题】:Inheritence of C++11 classC++11类的继承
【发布时间】:2017-03-16 22:08:27
【问题描述】:
#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 的单一默认构造函数的任何错误。

在 Neurosurgery 之后执行 First Surgery 构造函数。

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

我是否以错误的方式使用 c++11

【问题讨论】:

  • 从派生类中删除所有数据成员。

标签: c++ c++11 inheritance


【解决方案1】:

这是因为您声明了变量 price 和 type 的两倍,并且当您调用 cout &lt;&lt; var1.getPrice() &lt;&lt; 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 变量的值。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      相关资源
      最近更新 更多