slicing problem
代码
class Base{
public:
Base():m(0){};
//Base(const Base& rhs):m(rhs.m){cout<<"Copy constructor, rhs is "<<&rhs<<" this pointer is "<<this<<endl;}
void add(){m++;};
int m;
};
class Derived : public Base{};
int main(){
Derived d;
cout<<d.m<<endl;
static_cast<Base&>(d).add();
cout<<d.m<<endl;
//so called "slicing problem"
static_cast<Base>(d).add();
//Base(static_cast<Base&>(d)).add();
cout<<d.m<<endl;
return 0;
}
嘿嘿,猜猜看static_cast<Base>(d).add(); 这一行,编译器到底干了些什么.