1 include<iostream> 2 #include<string> 3 using namespace std; 4 class parent{ 5 protected: 6 int mv; 7 public: 8 parent(){ 9 mv = 100; 10 } 11 int value(){ 12 return mv; 13 } 14 }; 15 class child:public parent{ 16 public: 17 int addvalue(int v){ 18 mv = mv + v; 19 } 20 int changemv(int v){ 21 mv = v; 22 } 23 }; 24 int main(){ 25 parent p; 26 child c; 27 cout << "c.value()=" << c.value() << endl;//100 28 cout << "p.value()=" << p.value() << endl;//100 29 c.addvalue(250); 30 cout << "c.value()=" << c.value() << endl;//350 31 cout << "p.value()=" << p.value() << endl;//100 32 cout << "c.changemv()后" << endl; 33 c.changemv(380); 34 cout << "c.mv=" << c.value() << endl;//380 35 cout << "p.mv=" << p.value() << endl;//100 36 return 0; 37 }
运行结果:
c.value()=100
p.value()=100
c.value()=350
p.value()=100
c.changemv()后
c.mv=380
p.mv=100
结论:
对于具有继承关系的类,父类和子类各自有各自的成员变量,子类对其成员变量的修改并不会影响父类的
原文:https://www.cnblogs.com/DXGG-Bond/p/11915495.html