C++:explicit关键字:修订间差异

来自WHY42
imported>Soleverlee
无编辑摘要
imported>Soleverlee
无编辑摘要
 
第1行: 第1行:
explicit '''美[ɪkˈsplɪsɪt]''' 关键字用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换。
explicit '''美[ɪkˈsplɪsɪt]''' 关键字用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换。
 
=作用=
explicit使用注意事项:
explicit使用注意事项:
*explicit 关键字只能用于类内部的构造函数声明上。
*explicit 关键字只能用于类内部的构造函数声明上。
第18行: 第18行:
</source>
</source>


=用法=
以下是CEGUI里面的一处,挺有意思:
<source lang="cpp">
// allocated object is just a stub template class if custom memory allocators aren't used
template<typename Allocator>
class AllocatedObject
{
public:
    inline explicit AllocatedObject()
{}
};
</source>
[[Category:Programe]]
[[Category:Programe]]

2015年11月7日 (六) 07:26的最新版本

explicit 美[ɪkˈsplɪsɪt] 关键字用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换。

作用

explicit使用注意事项:

  • explicit 关键字只能用于类内部的构造函数声明上。
  • explicit 关键字作用于单个参数的构造函数。
  • 在C++中,explicit关键字用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换
class String{
      explicit String(int n);
      String(const char *p);
};
String s1 = 'a';       //错误:不能做隐式char->String转换
String s2(10);         //可以:调用explicit String(int n);
String s3 = String(10);//可以:调用explicit String(int n);再调用默认的复制构造函数
String s4 = "Brian";   //可以:隐式转换调用String(const char *p);再调用默认的复制构造函数
String s5("Fawlty");   //可以:正常调用String(const char *p);

用法

以下是CEGUI里面的一处,挺有意思:

// allocated object is just a stub template class if custom memory allocators aren't used
template<typename Allocator>
class AllocatedObject
{
public:
    inline explicit AllocatedObject()
	{}
};