2016-04-01 17 views
-2
#include <iostream> 
#include <string> 
using namespace std; 

class parent 
{ 
    int x=0; 
    public: 
    int getx() 
    { 
     return x; 
    } 
}; 

class child : public parent 
{ 
    int x=7; 
}; 
int main() 
{ 
    parent cat; 
    cout << cat.getx(); 
    child s; 
    cout << s.getx(); //stops working here 
    return 0; 
} 

這是我遇到的問題的示例。爲什麼不打印7當我調用cout < < getx()作爲派生對象?當我將父方法作爲派生對象調用時出現C++錯誤

+2

有沒有辦法,直到你發佈你的'Stack'和'LinkedList'代碼,以及你的意思來回答這個問題:「停止工作」。 –

+0

我編輯了帖子,顯示了一個與我目前遇到的問題非常相似的例子。 – dfries

+0

似乎可以爲我工作 - [demo](https://ideone.com/TMUSfv) –

回答

-1
#include <iostream> 
#include <string> 

class parent 
{ 
protected: 
    int m_x; 
public: 
    parent(int x = 0) : m_x(x) {} 
    int getx(){return m_x;} 
}; 
class child : public parent 
{ 
public: 
    child():parent(7){} 
}; 
int main() 
{ 
    parent cat; 
    std::cout << cat.getx() << std::endl; 

    child s; 
    std::cout << s.getx() << std::endl; 

    return 0; 
} 

結果

[email protected]:~/Develop/Test2$ make getx 
g++  getx.cpp -o getx 
[email protected]:~/Develop/Test2$ ./getx 
0 
7 
相關問題