Last active
August 29, 2015 14:21
-
-
Save MasazI/e931d612d09b8edaac39 to your computer and use it in GitHub Desktop.
explicit.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment