C++ 如何使用Parent';儿童中的变量是什么?

C++ 如何使用Parent';儿童中的变量是什么?,c++,class,C++,Class,关于X类 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-&

关于X类

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中。

您必须在
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;
}
#包括
X类
{
受保护的:
int abc=10;
公众:
X(){};
~X(){};
int getAbc(){return abc;}
};
Y类:公共X类
{
公众:
国际广播公司;
X&X;
Y(X&X):X(X){
};
~Y(){};
void setAbcofY(){this->abc=X::getAbc();}
};
int main()
{
X*a=新的X();
Y*b=新Y(*a);
b->setAbcofY();
//系统(“暂停”);

std::cout abc欢迎使用Stack Overflow。请花时间阅读并参考您可以在此处询问的内容和方式。您的示例中
a
是什么?还要注意
b->setAofY();
是未定义的行为,即使您的代码可以编译。抱歉,这是我的错误。我已经编辑过。我仍然不知道
a
是在哪里定义的?而且
b->setAofY();
仍然是UB。我已经修复了返回a;->返回abc;我正确地向上推了一票,但我不知道为什么要向下推一票