2017-05-26 20 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 –

相关问题