explicitは引数を1つだけとる変換コンストラクタが暗黙的に呼ばれることを防ぐ。
よくあるケース
- explicitを記述しない変換コンストラクタをもつクラスは、= で初期化(コンストラクタ呼び出し)を記述できる
- クラスの参照を引数に受け取る場合、意図せずして暗黙的に変換コンストラクタが呼び出されることがある
This file contains 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; | |
} |
0 件のコメント:
コメントを投稿