使用static_cast运算符将子类转换为父类即可
1 #include <iostream> 2 3 using namespace std; 4 5 class Base 6 { 7 public: 8 Base(int p_n) : n(p_n) { } 9 Base& operator=(const Base &base) 10 { 11 n = base.n; 12 return *this; 13 } 14 15 friend ostream& operator<<(ostream &os, const Base &base) 16 { 17 os << "n: " << base.n; 18 return os; 19 } 20 private: 21 int n; 22 }; 23 24 class Sub : public Base 25 { 26 public: 27 Sub(int p_n, int p_m) : Base(p_n), m(p_m) { } 28 Sub& operator=(const Sub &sub) 29 { 30 Base::operator=(static_cast<Base>(sub) ); 31 m = sub.m; 32 return *this; 33 } 34 35 friend ostream& operator<<(ostream &os, const Sub &sub) 36 { 37 os << static_cast<Base>(sub) << ", "; 38 os << "m: " << sub.m; 39 return os; 40 } 41 private: 42 int m; 43 }; 44 45 int main() 46 { 47 Sub sub1(5, 6); 48 Sub sub2(-5, -6); 49 50 cout << sub2 << endl; 51 sub2 = sub1; 52 cout << sub2 << endl; 53 54 return 0; 55 }
运行结果:
n: -5, m: -6
n: 5, m: 6