// // explicit.cpp // CplusplusPractice // // Created by masai on 2015/05/23. // Copyright (c) 2015年 masai. All rights reserved. // #include <iostream> using namespace std; class X { public: X(int x){} }; class Y{ public: Y(const X& x){} }; class Str{ public: Str(const char* str){str_ = str;} ~Str(){} const char* toChar() const{ return str_; }; private: const char* str_; }; class StrExplicit{ public: explicit StrExplicit(const char* str){str_ = str;} ~StrExplicit(){} const char* toChar() const{ return str_; } private: const char* str_; }; int main(int argc, char* argv[]){ // Yにintを指定しても、Xの変換コンストラクタが暗黙的に呼ばれ、X(3) を代入したことと同じになる Y(3); // 変換コンストラクタが暗黙的に呼ばれる(ただし、operator=とは異なる) Str s = "abc"; cout << s.toChar() << endl; //StrExplicit se = "efg"; // NG(暗黙的にコンストラクタを呼べないため、コンパイルエラー) //cout << se.toChar() << endl; StrExplicit se("efg"); cout << se.toChar() << endl; }