如何用派生类object更改基类变量
How to change the base class variables with the derived class object-c++
#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
的临时实例,它与派生的类无关。只需将a2
从get()
中的任何地方移除并尝试它。您将能够看到正在发生的变化。
[注:基类对象在分配派生对象时自动分配。这意味着当您执行new B
时,它将为B
和A
分配内存]
编辑:
对于你的问题,你的get()
应该是这样的:
void get()
{
a=10;
b=20;
c=30;
cout<<a<<b<<c<<endl;
cout<<"Checking!"<<endl;
}
相关文章:
- Qml 未收到基类成员变量的更新值
- 我如何实现从其基类获取变量的构造函数
- 变量(继承自基模板类)的偏移量,由具有相同名称的成员遮蔽
- 如何从派生类中的基类访问变量的值?
- 初始化基类和派生类中的类成员变量
- 决定对基类的变量指针进行函数调用
- 为什么我的基类指针变量不能访问派生类中的函数?
- 基类指针,访问派生的类成员变量
- 使用某些条件初始化派生类中的基类成员变量
- C++类函数继承使用从基类继承的另一个类的变量
- 我需要通过基类静态变量访问派生类成员
- 在派生类的构造函数的主体中初始化基类成员变量
- "Inherit"移动操作,而无需访问基类成员变量
- 在c++的派生类构造函数中访问基模板类中的变量
- 当基类具有两个或多个模板参数时,C++11 别名基模板类变量在模板派生类中不起作用
- 无法从c++基类访问变量
- 如何在派生类构造函数中初始化基类成员变量
- 抽象基类成员变量
- Shared_ptr对抽象基类(成员变量)是一个未声明的标识符
- 通过基类容器访问派生类唯一变量的最佳方式