65,208
社区成员
发帖
与我相关
我的任务
分享
class FBase
{
public:
virtual void Set()
{
info = _T("FBase");
}
void PrintInfo()
{
_tprintf(_T("%s\n"), info);
}
protected:
TCHAR *info;
};
class FChild : public FBase
{
public:
void Set()
{
info = _T("FChild");
}
};
FChild child;
child.Set();
child.PrintInfo();
((FBase)child).Set();
child.PrintInfo();
FBase* pBase = (FBase*)&child;
FBase* pBase2 = &(FBase)child;
FBase* pBase3 = &(FBase)child;
FBase e(child); // copy construction
e.Set();
第一句就是复制构造发生的点。
using namespace std;
class TestClass
{
public:
TestClass(){ cout << "constructor..." << endl; }
TestClass(TestClass& b) { cout << "copy constructor..." << endl;}
TestClass& operator = (const TestClass& b)
{ cout << "assignment constructor..." << endl; return *this;}
};
void TestFunc(TestClass c){}
int _tmain(int argc, _TCHAR* argv[])
{
//调用一般的构造函数
TestClass obj1; //constructor
//创建对象并初始化,调用拷贝构造函数
TestClass Obj2(obj1); //copy constructor
TestClass Obj3 = obj1; //copy constructor
//传递参数,产生临时变量,调用拷贝构造函数
TestFunc(obj1); //copy constructor
//赋值操作,调用赋值构造函数
Obj3 = Obj2; //assignment constructor
return 0;
}
FBase(const FBase& b)
{
//Copy Constructor code...
}
在使用多态的时候不能使用这种对象的强制转换,而应该使用指针或者引用(楼主肯定知道^^)。如果非要深究,应该是这么回事:
FChild child;
child.Set();
child.PrintInfo(); //print: FChild
//对对象进行类型转换,调用默认的拷贝构造函数进行浅拷贝
//此时b.info 指向 child.info 内存地址
// b.vtable 指向 FBase::vtable
FBase b = (FBase)child;
b.PrintInfo(); //print: FChild
//给b.info 重新赋值,调用 FBase::Set()
b.Set();
b.PrintInfo(); //print: FBase
child.PrintInfo(); //print: FChild