用户定义的转换(User-defined Conversion)
是一种将一个类类型转换为另一种类型的机制
语法
operator conversion-type-id
explicit operator conversion-type-id (C++11)
示例
Integer.h
#pragma once #include <iostream> class Integer { friend std::ostream &operator<<(std::ostream &os, const Integer &integer); public: Integer(int i); operator int(); //user-defined conversion private: int i; };
Integer.cpp
#include "Integer.h" std::ostream &operator<<(std::ostream & os, const Integer & integer) { os << integer.i; return os; } Integer::Integer(int i) : i(i) { } Integer::operator int() { return i; }
UserDefinedConversionExample.cpp
#include "Integer.h" int main() { using namespace std; Integer integer = 20190224; cout << "integer: " << integer << endl; int i = integer; cout << "i: " << i << endl; system("pause"); return 0; }