converting constructor

converting constructor

当类的构造函数只有一个实参,就相当于有了一个隐式类型转换的方法

// lcl 20190611
// tmp.cpp
// show implicit converting caused by converting constructor
#include <iostream>
#include <string>
using namespace std;

class foo{
public:
  foo(string s): str(s) {}
  void add(const foo &f){str += f.str;}
  void print(){cout << str;}
private:
  string str;
};

int main(){
  string s = "something";
  foo f("here");
  f.add(s);
  f.print();
}

上例中foo类的f使用add成员函数,参数本应是另一个foo类,但是这里传入string对象仍然可以,就是因为有隐式的类型转换,而隐式的类型转换的来源在于有一个单参数的构造函数

一个要注意的地方是类类型转换只允许一步转换

  • f.add("sth")错误,因为需要字符串常量转成string,string再转foo,共两步。
  • f.add(string("sth"))正确
  • f.add(foo("sth"))正确

如果不希望发生这种隐式类型转换,需要在相关构造函数前加关键字 explicit,而且explicit关键字只能在类内定义或声明前加,不应在类外定义时重复。

class foo{
public:
  explicit foo(string s): str(s) {}
  void add(const foo &f){str += f.str;}
  void print(){cout << str;}
private:
  string str;
};

此时已经不会发生隐式转换,比如f.add(string("sth"))。然而仍可以做到显式强制转换

  • f.add(foo("sth"))正确
  • f.add(static_cast<foo>("sth")) 正确
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容