Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用基类对象设置派生类变量的值?_C++ - Fatal编程技术网

C++ 如何使用基类对象设置派生类变量的值?

C++ 如何使用基类对象设置派生类变量的值?,c++,C++,我需要通过aa的对象a将x=2000分配给B的x 这里B是派生类,即继承类A class A { public: int x, y; void print() { cout<<endl<<"print() of A"; } virtual void display() { cout<<endl<<"display() of A"; } }; class B:

我需要通过
a
a的对象
a将
x=2000
分配给
B的
x

这里B是派生类,即继承类A

 class A
{
public:
    int x, y;
    void print()
    {
        cout<<endl<<"print() of A";
    }
    virtual void display()
    {
        cout<<endl<<"display() of A";
    }
};
class B: public A
{
public:
    int x, z;
    void display()
    {
        cout<<endl<<"display() of B";
    }
    void print()
    {
        cout<<endl<<"print() of B";
    }
};
A类
{
公众:
int x,y;
作废打印()
{

C++中的CUT< P>,多态是通过虚函数实现的。如果需要通过指针或引用基类型来改变派生类中的某个类,则需要一个虚拟函数。(技术上,您不需要;您可以将其转换为派生类型,但这是设计失败的允许)。.

通过执行以下操作找到了答案:

((B *)aptr)->x = 2000;

这可以通过在基类中创建虚拟函数来实现,该虚拟函数影响调用派生类的函数进行初始化

#include<iostream>
#include<stdio.h>

using namespace std;

 class A
{
public:
    int x, y;
    void print()
    {
        cout<<endl<<"print() of A";
    }
    virtual void display()
    {
        cout<<endl<<"display() of A";
    }

    virtual void setX(int a)
    {

    }
};
class B: public A
{
public:
    int x, z;
    void display()
    {
        cout<<endl<<"display() of B";
    }

    void print()
    {
        cout<<endl<<"print() of B";
    }

    void setX(int a)
    {
        x=a;
    }
};


int main()
{
    A *ptr;
    B b;
    ptr=&b;
    ptr->setX(2000); ///using pointer object of class A 
    cout<<b.x;


}
#包括
#包括
使用名称空间std;
甲级
{
公众:
int x,y;
作废打印()
{
你似乎对虚拟函数有一些了解。继续试验它们,也许创建一个虚拟的
set_x
函数?这里我的display()是虚拟的。但是我必须通过基类对象将x=2000赋值给子类的变量。这可以通过((B*)aptr完成)->x=2000;这是指向对象的指针,但我需要通过一个只指向对象的指针的对象来实现。@Pete Becker