你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?

Hi...Shouldn't the id_public variable give the result as 81 & 86? Why is it taking up different memory locations for both the derive classes?

本文关键字:派生 两个 内存 位置 结果 不应该 public 变量 id 你好 为什么      更新时间:2023-10-16
#include <bits/stdc++.h>
using namespace std;
class Parent {
public:
int id_public;
};
class Child1 : public Parent {
public:
void setId(int id) {
id_public = id;
cout<<id_public<<endl;
}
};
class Child2 : public Parent {
public:
void setId2(int id) {
cout<<id_public<<endl;
id_public += id;
cout<<id_public<<endl;
}
};
int main() {
Child1 obj1;
Child2 obj2;
obj1.setId(81);
obj2.setId2(5);
return 0;
}

这与两个无关:您只有两个对象,每个对象都有自己的成员变量。一个变量必须是static才能共享(这是很少需要的(。