c语言有由用户定义类型,C语言中用户定义类型的顺序类型转换

此代码编译并运行公共隐式bool强制转换(在下面注释,在

http://ideone.com/FDJHB)或通过公共隐式int强制转换,后跟隐式int到bool强制转换(如下所示,

http://ideone.com/kHQ46).但是,将bool强制转换为私有(在下面注释,在

http://ideone.com/4poze)会导致编译错误.在这种情况下,为什么通过int的路由不再是一个选项?像这样的连续演员是否定义了行为?谢谢.

#include

class MyObject {

public:

MyObject(int theInt) : theInt_(theInt) {

return;

}

MyObject& operator=(MyObject& source) {

std::cout << "assign op" << std::endl;

theInt_ = source.theInt_;

return *this;

}

friend MyObject operator*(MyObject& lhs, MyObject& rhs);

operator int() {

std::cout << "int conv" << std::endl;

return theInt_;

}

/*

operator bool() {

std::cout << "bool conv" << std::endl;

return theInt_;

}

*/

private:

int theInt_;

MyObject(MyObject& source);

// operator bool();

};

MyObject operator*(MyObject& lhs, MyObject& rhs) {

std::cout << "mult op" << std::endl;

return MyObject(lhs.theInt_*rhs.theInt_);

}

int main(int argc, char* argv[]) {

MyObject a(1);

MyObject b(2);

MyObject c(3);

if (a * b = c) std::cout << "Oh-no!" << std::endl;

return 0;

}

编辑:根据要求,相关的编译器消息.

1)输出代码给定,转换为int到bool:

多操作

int conv

分配操作

int conv

不好了!

2)使用public bool cast输出代码:

多操作

int conv

分配操作

bool conv

不好了!

3)如果bool强制私有的编译器错误:

prog.cpp: In function ‘int main(int, char**)’:

prog.cpp:34: error: ‘MyObject::operator bool()’ is private

prog.cpp:50: error: within this context

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值