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

本文探讨C++中隐式类型转换的规则,通过一个具体的例子展示公共bool和int强制转换如何影响代码行为。当bool转换为私有时,通过int的间接转换路径不再可行,导致编译错误。这揭示了C++中强制转换和类型安全的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此代码编译并运行公共隐式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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值