class A {public:virtual A& operator= (const A& a) {assign(a);return *this;}
protected:void assign(const A& a) {// copy members of A from a to this}};
class B : public A {public:virtual B& operator= (const A& a) {if (const B* b = dynamic_cast<const B*>(&a))assign(*b);elsethrow bad_assignment();return *this;}
protected:void assign(const B& b) {A::assign(b); // Let A's assign() copy members of A from b to this// copy members of B from b to this}};
#include <iostream>
using namespace std;
// Base classclass A {public:A() {}A(const A& a) {cout << "'A' copy constructor" << endl;}virtual void run() const { cout << "I am an 'A'" << endl; }};
// Derived classclass B: public A {public:B():A() {}B(const B& a):A(a) {cout << "'B' copy constructor" << endl;}virtual void run() const { cout << "I am a 'B'" << endl; }};
void g(const A & a) {a.run();}
void h(const A a) {a.run();}
int main() {cout << "Call by reference" << endl;g(B());cout << endl << "Call by copy" << endl;h(B());}
输出是:
Call by referenceI am a 'B'
Call by copy'A' copy constructorI am an 'A'
class A{public:virtual void Say(){std::cout<<"I am A"<<std::endl;}};
class B: public A{public:void Say() override{std::cout<<"I am B"<<std::endl;}};
int main(){B b;A a1;A a2=b;
b.Say(); // I am Ba1.Say(); // I am Aa2.Say(); // I am A why???}