- /*=============================================================================
- # FileName: explicit_try.cc
- # Desc: 验证含有一个参数的非explicit构造函数是否可以拷贝初始化
- # Author: Dalei
- # Email: guoyunlei@live.com
- # HomePage:
- # Version: 0.0.1
- # History:
- =============================================================================*/
- #include <iostream>
- #include <string>
- #include <vector>
- using std::cout;
- using std::cin;
- using std::endl;
- using std::string;
- using std::vector;
- class People {
- public:
- People() = default;
- People(string s):name(s) { }
- string getName() const { return name; }
- static vector<string> &getVector() { return name_arr; }
- //隐式类型转换,用string生成一个临时量,因此可以绑定到const形参上
- static void addToVector(const People &p) {
- name_arr.push_back(p.getName());
- }
- private:
- string name = "";
- static vector<string> name_arr;
- };
- vector<string> People::name_arr = {};
- int main(int argc, const char *argv[])
- {
- People p;
- cout << "p :" << endl;
- cout << p.getName() << endl;
- People tom("tom");
- People::addToVector(tom);
- string Bob = "Bob";
- People::addToVector(Bob);//隐式类型转换
- //People::addToVector("Bob");//只允许一步的隐式类型转换
- vector<string> v = People::getVector();
- cout << "name_arr:" << endl;
- for (const auto &p : v) {
- cout << p << " ";
- }
- cout << endl;
- string myName = "guo";
- People guo = myName; //隐式类型转换允许拷贝初始化形式的转换
- cout << guo.getName() << endl;
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/0708201410159.html
来源: http://www.codesnippet.cn/detail/0708201410159.html