您的位置:首页 > 编程语言 > C语言/C++

C++ 类型自动转换 构造函数 复制构造函数 赋值操作运算符函数

2014-04-03 11:32 721 查看
什么都不说,直接上代码。

#pragma once
#include <iostream>

class Core
{
public:
Core(){ std::cout << __FUNCSIG__ << ":" << this<<std::endl; }
Core(const Core&){ std::cout << __FUNCSIG__ << ":" << this << std::endl; }
~Core(){ std::cout << __FUNCSIG__ << ":" << this << std::endl; }

Core* clone()const{ return new Core(*this); }
};


#pragma once
#include <iostream>

template <class T>
class Handle
{
public:
Handle() :ptr(NULL){ std::cout << __FUNCSIG__ << ":" << this << std::endl; }
Handle(T* t) :ptr(t){ std::cout << __FUNCSIG__ << ":" << this << std::endl; }
~Handle(){ std::cout << __FUNCSIG__ << ":" << this << std::endl; delete ptr; }
Handle(const Handle& ref){
std::cout << __FUNCSIG__ << ":" << this << std::endl;
ptr = ref.ptr ? ref.ptr->clone() : NULL;
}
Handle& operator=(const Handle& ref){
std::cout << __FUNCSIG__ << ":" << this << std::endl;
if (&ref != this)
{
delete ptr;
ptr = ref.ptr ? ref.ptr->clone() : NULL;
}
return *this;
}
private:
T* ptr;
};


#include <iostream>
#include "Core.h"
#include "Handle.h"

int main(int __argc, const char** __argv)
{
Handle<Core> h;
h = new Core();
std::cout << "-----------------" << std::endl;
Handle<Core> handle = new Core();
std::cout << "-----------------" << std::endl;
return EXIT_SUCCESS;
}
执行结果:
__thiscall Handle<class Core>::Handle(void):0023F8DC
__thiscall Core::Core(void):00541508
__thiscall Handle<class Core>::Handle(class Core *):0023F7C8
class Handle<class Core> &__thiscall Handle<class Core>::operator =(const class
Handle<class Core> &):0023F8DC
__thiscall Core::Core(const class Core &):00541538
__thiscall Handle<class Core>::~Handle(void):0023F7C8
__thiscall Core::~Core(void):00541508
-----------------
__thiscall Core::Core(void):00541508
__thiscall Handle<class Core>::Handle(class Core *):0023F8D0
-----------------
__thiscall Handle<class Core>::~Handle(void):0023F8D0
__thiscall Core::~Core(void):00541508
__thiscall Handle<class Core>::~Handle(void):0023F8DC
__thiscall Core::~Core(void):00541538
请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: