2017-05-26 38 views
-2

有關類X如何在Child中使用Parent變量的值?

class X 
{ 
protected: 
    int abc=10; 
public: 
    X() {}; 
    ~X() {}; 
    int getABC() { return abc; } 
}; 

關於Y類

class Y : public X 
{ 
public: 
    Y() {}; 
    ~Y() {}; 

    void setABC() { abc = X::getABC(); } 
}; 



void main() 
{ 
    Y* b; 
    b->setABC(); 
    system("pause"); 
    return; 
} 

我想把類X的變量ABC的值類Y的變量ABC

+2

歡迎來到堆棧溢出。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –

+0

你的例子中的'a'是什麼?還要注意,即使你的代碼會被編譯,'b-> setAofY();'也是未定義的行爲。 –

+0

抱歉,這是我的錯誤。 我已編輯。 –

回答

0

你必須在Y中儲存參考X。 也許這就是你想要做的:

#include <iostream> 

class X 
{ 
protected: 
    int abc=10; 
public: 
    X() {}; 
    ~X() {}; 
    int getAbc() { return abc; } 
}; 

class Y : public X 
{ 
public: 
int abc; 
X& x; 

    Y(X& x) : x(x) { 

}; 
    ~Y() {}; 

    void setAbcofY() { this->abc = X::getAbc(); } 
}; 

int main() 
{ 
    X* a = new X(); 
    Y* b = new Y(*a); 
    b->setAbcofY(); 
    //system("pause"); 
    std::cout << b->abc << std::endl; 
    return 0; 
} 
+0

thx非常多! –

+0

爲什麼downvote?請解釋! – mohe2015

+0

我推動upvote corretly,但我不知道爲什麼downvote –

相關問題