标签:master qq群 编译 ast 构造 重载 hub int() github
class Int{
public:
Int(int i = 0) : val(i){}
explicit operator int()const{return val;}
private:
int val;
};
Int ii(10);
int i = (int)ii;
如果不加explicit,就是下面的形式:
Int ii(10);
int i = ii;
例子:
#include <iostream>
/*---------test1------------- */
class Int{
public:
Int(int i = 0) : val(i){}
explicit operator int()const{return val;}
private:
int val;
};
/*---------test1------------- */
/*---------test2------------- */
struct A;
struct B{
operator A()const;
int val;
};
struct A{
A(int i = 0) : val(i){}
A(const B& b){
std::cout << "A copy" << std::endl;
val = b.val;
}
private:
int val;
};
B::operator A()const{
std::cout << "B cast" << std::endl;
return A(10);
}
A f(const A&){}
/*---------test2------------- */
int main(){
/*---------test1------------- */
Int i1;
i1 = 10;
int s = (int)i1 + 11;
std::cout << s << std::endl;
const Int i2(11);
int s1 = (int)i2;
/*---------test1------------- */
/*---------test2------------- */
B b1;
A a1 = f(b1);//编译应该不知道应该调用谁,但是从执行结果来看,是调用了类A的构造函数
//A a1 = f(b1.operator A());//告诉编译器调用类B类型转化运算符
//A a1 = f(A(b1));//告诉编译器调用类A的构造函数
/*---------test2------------- */
}
标签:master qq群 编译 ast 构造 重载 hub int() github
原文地址:https://www.cnblogs.com/xiaoshiwang/p/10180771.html