C语言中用户定义类型的顺序类型转换
发布时间:2020-12-16 09:39:33 所属栏目:百科 来源:网络整理
导读:此代码编译并运行公共隐式bool强制转换(在下面注释,在 http://ideone.com/FDJHB)或通过公共隐式int强制转换,后跟隐式int到bool强制转换(如下所示,http://ideone.com/kHQ46).但是,将bool强制转换为私有(在下面注释,在 http://ideone.com/4poze)会导致编译错误
此代码编译并运行公共隐式bool强制转换(在下面注释,在
http://ideone.com/FDJHB)或通过公共隐式int强制转换,后跟隐式int到bool强制转换(如下所示,http://ideone.com/kHQ46).但是,将bool强制转换为私有(在下面注释,在
http://ideone.com/4poze)会导致编译错误.在这种情况下,为什么通过int的路由不再是一个选项?像这样的连续演员是否定义了行为?谢谢.
http://ideone.com/kHQ46 #include <iostream> 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 解决方法
为了将您的类型转换为bool,编译器根据(相当复杂的)规则集选择“最佳”转换路径.
如果定义了运算符bool(),那么它提供了比运算符int()更好的转换,然后是从int到bool的转换;转换次数较少的路径被视为“更好”. 在此过程中不考虑可访问性,因此它将选择operator bool(),即使它是私有的.然后编译将失败,因为运算符bool()是私有的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |