c – 从指针转换为非标量对象类型?
发布时间:2020-12-16 10:04:07 所属栏目:百科 来源:网络整理
导读:有人可以解释为什么以下工作,尝试以下代码,它工作正常. class A { public : int32_t temp ; A ( bool y = false ) { }} ;int main ( int argc,char *argv[] ){ A temp ; temp = new A () ; temp.temp = 5 ; std::cout " " temp.temp std::endl ; return EXIT
有人可以解释为什么以下工作,尝试以下代码,它工作正常.
class A { public : int32_t temp ; A ( bool y = false ) { } } ; int main ( int argc,char *argv[] ) { A temp ; temp = new A () ; temp.temp = 5 ; std::cout << " " << temp.temp << std::endl ; return EXIT_SUCCESS; } // ---------- end of function main ---------- 解决方法
在你的情况下.编译器使用了
implicitly defined Copy/Move Assignment operator.首先使用带有bool的构造函数构造A和指针.
所有指针类型在C中都是implicitly convertible到bool.有两种方法可以防止这种废话: >显式构造函数 因此,你可以这样做: class A { public : int32_t temp ; explicit A( bool y = false ) { } //Additionally A(void*) = delete; }; 定义一个只删除void *的构造函数,在传递指针时,overload resolution的构造函数高于bool构造函数.因为只要你传递一个指针就会被重载决策选中,因为它被删除了,程序就会格式不正确. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |