C++特殊类设计与类型转换详细代码示例
<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>常见的特殊类的设计</li><ul class="second_class_ul"><li>1.请设计一个类,不能被拷贝</li><li>2.请设计一个类,只能在堆上创建对象</li><li>3.请设计一个类,只能在栈上创建对象</li><li>4. 请设计一个类,不能被继承</li><li>5.请设计一个类,只能创建一个对象(单例模式)</li><ul class="third_class_ul"><li>设计模式:</li><li>单例模式:</li></ul></ul><li>C++中的类型转换</li><ul class="second_class_ul"><li>1.C语言中的类型转换</li><ul class="third_class_ul"></ul><li>2.为什么C++需要四种类型转换</li><ul class="third_class_ul"></ul><li>3.C++强制类型转换</li><ul class="third_class_ul"><li>3.1 stacit_cast</li><li>3.2 reinterpret_cast</li><li>3.3 const_cast</li><li>3.4 dynamic_cast</li></ul><li>4.RTTI(了解)</li><ul class="third_class_ul"></ul><li>5.常见面试题</li><ul class="third_class_ul"></ul></ul><li>总结 </li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>常见的特殊类的设计</h2><p class="maodian"></p><h3>1.请设计一个类,不能被拷贝</h3>
<blockquote><p>拷贝只会发生在两个场景中:拷贝构造函数以及赋值运算符重载,<strong>因此想要让一个类禁止拷贝,只需要让该类不能调用拷贝构造函数以及赋值运算符重载即可。</strong></p></blockquote>
<p><strong>C++98写法:</strong></p>
<blockquote><p>将拷贝构造函数与赋值运算符重载<strong>只声明不定义</strong>,并且将其<strong>访问权限设置为私有</strong>即可。</p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">class CopyBan
{
//...
private:
CopyBan(const CopyBan& c);
CopyBan& operator=(const CopyBan& c);
//...
};</pre></div>
<blockquote><p>原因:1.设置成私有:如果只声明没有设置成private,用户自己如果在类外定义了,就不能禁止拷贝了。</p>
<p>2.只声明不定义:不定义是因为该函数根本不会调用,定义了其实也没有什么意义,不写反而还简单,而且如果定义了就不会防止成员函数内部拷贝了。</p></blockquote>
<p><strong>C++11写法:</strong></p>
<blockquote><p>C++11扩展delete的用法,delete除了释放new申请的资源外,如果在默认成员函数后面跟上=delete,表示让编译器删除掉该默认成员函数。</p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">class CopyBan
{
//...
CopyBan(const CopyBan& c)=delete;
CopyBan& operator=(const CopyBan& c)=delete;
//...
};</pre></div>
<p class="maodian"></p><h3>2.请设计一个类,只能在堆上创建对象</h3>
<p><strong>实现方式:</strong></p>
<blockquote><p><strong>1.将类的构造函数设置为私有,拷贝构造声明成私有。防止别人调用拷贝在栈上生成对象。</strong></p>
<p><strong>2.提供一个静态的成员函数,在该静态成员函数中完成堆对象的创建。</strong></p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">class HeapOnly
{
public:
static HeapOnly* CreateHeapObj()
{
return new HeapOnly;
}
private:
HeapOnly()
{ }
//C++98方式
//1.只声明,不实现。因为实现可能会很麻烦,而你本身并不需要
//2.声明成私有
HeapOnly& operator=(const HeapOnly&);
//C++11方式
HeapOnly& operator=(const HeapOnly&) = delete;
};</pre></div>
<p class="maodian"></p><h3>3.请设计一个类,只能在栈上创建对象</h3>
<blockquote><p>方法:同上述将构造函数私有化,然后设计静态方法创建对象返回即可。</p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">class StackOnly
{
public:
static StackOnly CreateStackObj()
{
return StackOnly();
}
//禁掉operator new可以把下面用new 调用拷贝构造申请对象给禁掉
//StackOnly obj = StackOnly::CreateStackObj();
//StackOnly* ptr = new StackOnly(obj);
void* operator new(size_t size) = delete;
void operator delete(void* p) = delete;
private:
StackOnly()
:_a(0)
{ }
int _a;
};</pre></div>
<p class="maodian"></p><h3>4. 请设计一个类,不能被继承</h3>
<p><strong>C++98方式:把类的构造函数私有化,派生类调不到基类的构造函数就无法继承。</strong></p>
<div class="jb51code"><pre class="brush:cpp;">C++98中构造函数私有化,派生类中调不到基类的构造函数,则无法继承
class NonInherit
{
public:
static NonInherit GetInstance()
{
return NonInherit();
}
private:
NonInherit()
{ }
};</pre></div>
<p><strong>C++11方法:final关键字,final修饰类,表示该类不能被继承。ps(final还能修饰虚函数,表示该虚函数不能被重写。)</strong></p>
<div class="jb51code"><pre class="brush:cpp;">final 关键字:final修饰类,表示该类不能被继承。
class A final
{
//..
};</pre></div>
<p class="maodian"></p><h3>5.请设计一个类,只能创建一个对象(单例模式)</h3>
<p class="maodian"></p><h4>设计模式:</h4>
<blockquote><p>设计模式(Design Pattern)是一套<strong><span>被反复使用、多数人知晓的、经过分类的、代码设计经验的总结。</span></strong>为什么会产生设计模式这样的东西呢?就像人类历史发展会产生兵法。最开始部落之间打仗时都是人拼人的对砍。后来春秋战国时期,七国之间经常打仗,就发现打仗也是有套路的,后来孙子就总结出了《孙子兵法》。孙子兵法也是类似。</p></blockquote>
<blockquote><p>使用<strong>设计模式的目的</strong>:<strong><span>为了代码可重用性、让代码更容易被他人理解、保证代码可靠性。</span></strong>设计模式使代码编写真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。</p></blockquote>
<p class="maodian"></p><h4>单例模式:</h4>
<blockquote><p><strong><span>一个类只能创建一个对象,即单例模式。该模式可以保证系统中该类只有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享。</span></strong>比如:在某个服务器程序中,该服务器的配置信息存放在一个文件中,这些配置数据由一个单例对象统一读取,然后服务进程中的其他对象再通过这个单例对象获取这些配置信息,这种方式简化了在复杂环境下的配置管理。</p></blockquote>
<p>单例模式有两种实现模式:</p>
<blockquote><h6>1.<strong>饿汉模式</strong>:</h6>
<p><strong>(一开始(main函数之前)就创建单例对象)</strong></p>
<p><strong>就是说不管你将来用还是不用,程序启动时就会创建一个唯一的实例对象</strong>。</p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">饿汉模式
优点:简单
缺点:可能会导致进程启动慢,且如果有多个单例类对象实例启动顺序不确定。
class Singleton
{
public:
static Singleton* GetInstance()
{
return &m_instance;
}
private:
//构造函数私有化
Singleton(){}
//C++98防止拷贝
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
//or
//C++11
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton m_instance;
};
Singleton Singleton::m_instance;//在程序入口之前就完成单例对象的初始化</pre></div>
<blockquote><p>但是如果这个单例对象再多线程高并发环境下频繁使用,性能要求比较高,那么显然使用饿汉模式来避免资源竞争,提高响应速度更好。</p></blockquote>
<p>2.懒汉模式:</p>
<blockquote><p>如果单例对象构造十分耗时或者占用很多资源,比如加载插件啦,初始化网络连接啦,读取文件啦等等,而有可能该对象程序运行时不会用到,那么也要在程序一开始就进行初始化,就会导致程序启动时非常的缓慢。所以这种情况就使用<strong><span>懒汉模式(延迟加载)</span></strong>更好。</p></blockquote>
<blockquote><p><strong>懒汉模式也会有线程安全问题,在第一次初始化的时候要加锁</strong>。</p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">class Singleton
{
public:
static Singleton* GetInstance()
{
注意这里一定要使用Double-Check的方式加锁,才能保证效率和线程安全
if (nullptr == m_pInstance)
{
m_mtx.lock();//or--- unique_lock<mutex> lock(m_mtx);
if (nullptr == m_pInstance)
{
m_pInstance = new Singleton();
}
m_mtx.unlock();
}
}
//实现一个内嵌的垃圾回收类
class CGarbo
{
public:
~CGarbo()
{
if (Singleton::m_pInstance)
delete Singleton::m_pInstance;
}
};
//定义一个静态成员变量,程序结束时,系统自动调用它的析构函数从而释放单例对象
static CGarbo Garbo;
main函数结束,调用它的析构,从而释放单例对象
private:
//构造函数私有化
Singleton(){}
//防止拷贝
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* m_pInstance;//单例对象指针
static std::mutex m_mtx; //互斥锁
};
Singleton* Singleton::m_pInstance = nullptr;
Singleton::CGarbo Garbo;
std::mutex Singleton::m_mtx;</pre></div>
<blockquote><p>C++11中创建单例(懒汉模式)最简单的方法</p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">class Singleton
{
public:
局部的静态对象,是在第一次调用时初始化
static Singleton& GetInstance()
{
static Singleton inst;
return inst;
}
private:
Singleton()
{
std::cout << "Singleton" << std::endl;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};</pre></div>
<blockquote><p>C++11之前,这个代码是不安全的,编译器不支持。</p>
<p><strong>C++11之后,可以保证局部静态对象的初始化是线程安全的,只初始化一次。(C++11之后这个操作变成原子的了。)</strong></p></blockquote>
<p class="maodian"></p><h2>C++中的类型转换</h2>
<p class="maodian"></p><h3>1.C语言中的类型转换</h3>
<blockquote><p>在C语言中,如果<strong>赋值运算符左右两侧类型不同,或者形参与实参类型不匹配,或者返回值类型与接收返回值类型不一致时,就需要发生类型转换</strong>,C语言中总共有两种形式的类型转换:<strong><span>隐式类型转换和显式类型转换。</span></strong></p></blockquote>
<blockquote><p><strong>1.隐式类型转换:编译器在编译阶段自动进行,能转就转,不能转就编译失败。</strong></p>
<p><strong>2.显式类型转换:需要用户自己处理。</strong></p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">void Test()
{
int i = 1;
//隐式类型转换
double d = i;
printf("%d,%.2lf\n", i, d);
int* p = &i;
//显式类型转换
int address = (int)p;
printf("%x,%d\n", p, address);
}</pre></div>
<blockquote><p><strong>缺陷:转换的可视性比较差,所有的转换形式都是以一种相同形式书写,难以跟踪错误的转换。</strong></p></blockquote>
<p class="maodian"></p><h3>2.为什么C++需要四种类型转换</h3>
<p><strong>C风格的转换形式很简单,但是有不少缺点:</strong></p>
<blockquote><p><strong>1.隐式类型转换有些情况下可能会出问题:比如说数据精度的丢失。</strong></p>
<p><strong>2.显式类型转换将所有情况混合在一起,代码不够清晰。</strong></p></blockquote>
<blockquote><p>因此C++提出了自己的类型转换的风格,注意<strong>C++要兼容C语言,所以在C++中还是可以使用C语言那一套的类型转换</strong>。</p></blockquote>
<p class="maodian"></p><h3>3.C++强制类型转换</h3>
<blockquote><p><strong>标准C++为了加强类型转换的可视性,引入了四种命名的强制类型转换操作符:</strong></p></blockquote>
<p><strong><span>static_cast , reinterpret_cast , const_cast , dynamic_cast</span></strong></p>
<p class="maodian"></p><h4>3.1 stacit_cast</h4>
<blockquote><p><strong><span>static_cast用于非多态类型的转换(静态转换)</span></strong>,<strong>编译器隐式执行的任何类型转换都可用static_cast</strong>,<strong>但它不能用于两个不相关的类型进行转换</strong>。(<strong><span>用于两个相关类型/相近类型之间,C里的隐式类型转换都可用这个static_cast强转。</span></strong>)</p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">int main()
{
double d = 12.34;
int a = static_cast<int>(d);
std::cout << a << std::endl;
return 0;
}</pre></div>
<p class="maodian"></p><h4>3.2 reinterpret_cast</h4>
<blockquote><p><strong>reinterpret_cast操作符通常为操作数的位模式提供较低层次的重新解释,用于将一种类型转换为另一种不同的类型。(<span>可用于两个不相关类型之间进行强转。</span>)</strong></p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">int main()
{
double d = 12.34;
int a = static_cast<int>(d);
std::cout << a << std::endl;
这里使用static_cast会报错,应该使用reinterpret
//int* p = static_cast<int*>(a);
int* p = reinterpret_cast<int*>(a);
return 0;
}</pre></div>
<p class="maodian"></p><h4>3.3 const_cast</h4>
<blockquote><p><strong>const_cast<span>最常用的用途就是删除变量的const属性</span>,方便赋值。(<span>去掉const属性。</span>)</strong></p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">int main()
{
const int a = 2;
int* p = const_cast<int*>(&a);
*p = 3;
std::cout << a << std::endl;
return 0;
}</pre></div>
<p class="maodian"></p><h4>3.4 dynamic_cast</h4>
<blockquote><p><strong><span>dynamic_cast用于将一个父类对象的指针/引用转换为子类对象的指针或引用(动态转换)。</span></strong></p></blockquote>
<blockquote><p>向上转型:子类对象指针/引用 ->父类指针/引用(不需要转换,赋值兼容规则)。</p>
<p>向下转型:父类对象指针/引用->子类指针/引用(用dynamic_cast转型是安全的)。</p></blockquote>
<p><strong>注意:</strong></p>
<blockquote><p><span>1.dynamic_cast</span><strong><span>只能用于父类含有虚函数的类</span></strong><span>。</span></p>
<p><span>2.dynamic_cast</span><strong><span>会先检查是否能转换成功,能成功则转换,不能则返回0</span></strong><span>。</span></p></blockquote>
<div class="jb51code"><pre class="brush:cpp;">Base* b = new Derived();b实际上指向Derived对象
情况1:成功转换
Derived* d1 = dynamic_cast<Derived*>(b);
成功:b实际指向Derived对象,d1是有效的Derived指针
情况2:转换失败
Base* b2 = new Base();// b2指向纯Base对象
Derived* d2 = dynamic_cast<Derived*>(b2);
失败:b2不是Derived对象,d2 == nullptr</pre></div>
<div class="jb51code"><pre class="brush:cpp;">class A
{
public:
virtual void f(){}
};
class B :public A
{};
void fun(A* pa)
{
//dynamic_cast会先检查是否能成功转换成功,能成功则转换,不能则返回
B* pb1 = static_cast<B*>(pa);
B* pb2 = dynamic_cast<B*>(pa);
std::cout << "pb1:" << pb1 << std::endl;
std::cout << "pb2:" << pb2 << std::endl;
}
int main()
{
A a;
B b;
fun(&a);
fun(&b);
return 0;
}</pre></div>
<p><strong>注意:</strong></p>
<blockquote><p><strong><span>强制类型转换关闭或挂起了正常的类型检查</span></strong>,每次使用强制类型转换前,程序员应该仔细考虑是否还有其他不同的方法达到同一目的,如果非强制类型转换不可,则应限制强制类型转换值的作用域,以减少发生错误的机会。<strong><span>强烈建议:避免使用强制类型转换</span></strong>。</p></blockquote>
<p class="maodian"></p><h3>4.RTTI(了解)</h3>
<p>RTTI:Run-time Type identification的简称,即:<strong>运行时类型识别</strong>。</p>
<p><strong>C++通过一下方式来支持RTTI:</strong></p>
<blockquote><p><strong>1.typeid运算符。</strong></p>
<p><strong>2.dynamic_cast运算符。</strong></p>
<p><strong>3.decltype。</strong></p></blockquote>
<p class="maodian"></p><h3>5.常见面试题</h3>
<p>1.C++中的四种类型转换分别是:<strong>static_cast,reinterpret_cast,const_cast,dynamic_cast</strong>。</p>
<p>2.说说四种类型转换的应用场景。</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026010710313428.png" /></p>
<blockquote><p><strong>static_cast适用于两种类型相近的强制转化,dynamic_cast适用于多态类型的向下转换(安全检查)(向上转换本来就是安全的)。cosnt_cast适用于删除变量的const属性。reinterpret_cast适用于任意类型之间的转换(危险)。</strong></p></blockquote>
<p class="maodian"></p><h2>总结 </h2>
<p>到此这篇关于C++特殊类设计与类型转换的文章就介绍到这了,更多相关C++特殊类设计与类型转换内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
<div class="art_xg">
<b>您可能感兴趣的文章:</b><ul><li>C++强制类型转换的四种方式</li><li>解析C++中四种强制类型转换的区别详解</li><li>基于c++强制类型转换的(总结)详解</li><li>C++中的四种类型转换</li><li>C++中4种强制类型转换的区别总结</li><li>解决易语言转换到C++ 自定义数据类型</li></ul>
</div>
</div>
<!--endmain-->
頁:
[1]