Created
August 1, 2012 07:55
-
-
Save draftcode/3224733 to your computer and use it in GitHub Desktop.
Conversion FunctionとConstructor
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
| #include <iostream> | |
| using namespace std; | |
| struct C; | |
| struct D { | |
| operator C(); | |
| }; | |
| struct C { | |
| C() {} | |
| C(D) { | |
| cout << "constructor C(D)" << endl; | |
| } | |
| }; | |
| D::operator C() { | |
| cout << "operator C" << endl; | |
| return C(); | |
| } | |
| void f(C c) {} | |
| int main() { | |
| D d; | |
| // CはDのConversion Functionとコンストラクタのどちらの方法でも生成可能 | |
| f(static_cast<C>(d)); | |
| f((C) d); | |
| f(C(d)); | |
| f(d); | |
| // このままだと一番下の式でerror: conversion from 'D' to 'C' is ambiguousとな | |
| // りコンパイルエラー | |
| // コンストラクタC(D)をexplicitにすると | |
| // | |
| // f(static_cast<C>(d)); // constructor C(D) | |
| // f((C) d); // constructor C(D) | |
| // f(C(d)); // constructor C(D) | |
| // f(d); // operator C | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment