当将一个派生类强制转换成基类类型的时候,转换方式不一样会产生不一样的效果。例如该代码:static_cast<base&>(*this) ;
base 是基类,这句代码是将当前对象强制转化为积累类型的对象的引用,这样的话不会再次调用基类的构造函数。若转换成基类对象那就要调用基类的构造函数并创建出新的对象来了。
完整的代码:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <cstdlib>
#include "stdio.h"
#include <string>
#include <iostream>
using namespace std;
class A
{
public:
A():i_(0)
{
i_++;
cout << " A::A() is Exce." << endl;
}
A(int i) : i_(i)
{
i_++;
}
virtual ~A()
{
i_--;
cout << " A::~A() is Exce." << endl;
}
public:
int i_;
};
class B : public A
{
public:
B():j_(0)
{
j_++;
cout << " B::B() is Exce." << endl;
}
B(int j) : A(j) , j_(j)
{
j_++;
}
~B()
{
j_--;
cout << " B::~B() is Exce." << endl;
}
public:
int j_;
};
int main(int argc, char *argv[])
{
B *b1 = new B(5);
B *b2 = new B(8);
cout << "before changer " << endl;
cout << "b1.i_ = " << b1->i_ << endl;
cout << "b1.j_ = " << b1->j_ << endl;
static_cast<A&>(*b1) = (*b2);
cout << "affter changer " << endl;
cout << "b1.i_ = " << b1->i_ << endl;
cout << "b1.j_ = " << b1->j_ << endl;
return 0;
}
输出的结果是
before changer
b1.i_ = 6
b1.j_ = 6
affter changer
b1.i_ = 9
b1.j_ = 6
由此可见, static_cast<A&>(*b1) = (*b2); 类型转换完成之后的赋值操作知识将基类的变量进行了赋值,当然,前提是基类没有重载“=”运算符的时候,不会涉及到派生类。