如何用派生类object更改基类变量

How to change the base class variables with the derived class object-c++

本文关键字:基类 类变量 object 何用 派生      更新时间:2023-10-16
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
  int a,b,c;
  A()
  {
      a=0;
      b=0;
      c=0;
  }
};
class B:public A
{
public:
    void get()
    {
        A *a2 =new A;
        a2->a=10;
        a2->b=20;
        a2->c=30;
        cout<<a2->a<<""<<a2->b<<""<<a2->c<<""<<endl;
        cout<<"Checking!"<<endl;
    }
};
int main()
{
    A *a1 = new A;
    B *b1 = new B;
    cout<<a1->a<<""<<a1->b<<""<<a1->c<<""<<endl;
    b1->a=10;
    b1->b=20;
    b1->c=30;
    cout<<b1->a<<""<<b1->b<<""<<b1->c<<""<<endl;
    b1->get();//cant able to change the variables of the base class object with the derived class object
    cout<<a1->a<<""<<a1->b<<""<<a1->c<<""<<endl;//will print the same values..
    //b1->get();
    return 0;
}
输出:

<>之前000102030102030检查!000按任意键继续…之前

//派生类对象持有的变量的地址与基类对象持有的变量的地址不同。//但是有没有可能通过派生类对象来改变基类的变量

为什么在get函数中创建一个新的a,只是:

cout << a << b << c << "n";

或者如果你想更明确:

cout << this->a << this->b << this->c << "n";

在您的get()方法中,您实际上是在创建Base class A的临时实例,它与派生的类无关。只需将a2get()中的任何地方移除并尝试它。您将能够看到正在发生的变化。

[注:基类对象在分配派生对象时自动分配。这意味着当您执行new B时,它将为BA分配内存]

编辑:

对于你的问题,你的get()应该是这样的:

void get()
{
    a=10;
    b=20;
    c=30;
    cout<<a<<b<<c<<endl;
    cout<<"Checking!"<<endl;
}