2017-03-16 61 views
-1
#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的繼承C++類11

我做了非常簡單的,以避免與常量,singlone默認構造函數的任何錯誤。

第一手術構造函數在神經外科手術後執行。

神經外科構造函數應該覆蓋缺省的手術構造函數所做的值。

正在使用C++ 11的錯款式我

+4

刪除派生類中的所有數據成員。 –

回答

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變量的值。

1

這是由以下事實造成的,它不是虛擬的,也有具有相同名稱的多個變量。所以你從基礎手術中獲得價值。其他類也定義了具有相同名稱的變量。我認爲最簡單的解決方案是:將受保護的變量保存在基類中,並從子類中移除這些變量。