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 请按任意键继续. . .
相关文章推荐
- C++ 转换类型运算符 调用构造函数实现的类型转换
- C++回顾之内联函数及新类型转换运算符
- C++ Pirmer : 第十四章 : 重载运算符与类型转换之函数调用运算符与标准库的定义的函数对象
- C++ 转换类型运算符 调用构造函数将变量转化成为一个对象的成员变量
- C++回顾之内联函数及新类型转换运算符
- c++中的类型转换和字符串相应操作函数
- 从赋值操作理解不同类型的函数传参
- C++中四种类型转换运算符详解
- 如何在编译时刻判断两个类型是否可以自动转换?——《Modern C++ Design》读书笔记(1)
- C++重载函数(函数匹配与实参类型转换)
- [C++]复制构造函数、赋值操作符与隐式类类型转换
- c++的类型转换和运算符
- C++中复制构造函数与重载赋值操作符
- C++ 学习之构造函数:构造函数小结3 默认构造函数、隐式类型转换和复制构造函数
- C++的类型转换运算符(一)——static_cast 与 dynamic_cast
- C++:关于C++的四个类型转换运算符
- C++中函数调用中构造函数、析构函数、赋值过程
- 转战JS(1) 初探与变量类型、运算符、常用函数与转换
- C++ 类型转换运算符
- 读书笔记 effective c++ Item 24 如果函数的所有参数都需要类型转换,将其声明成非成员函数