从指针到非标量对象类型的转换

Conversion From Pointer To NonScalar Object Type?

本文关键字:类型 转换 对象 标量 指针      更新时间:2023-10-16

谁能解释一下为什么下面的工作,试了下面的代码,它工作得很好。

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  ----------

在你的情况下。编译器使用隐式定义的拷贝/移动赋值操作符。它首先使用带bool的构造函数用指针构造A


所有指针类型在c++中隐式转换为bool。有两种方法可以防止这种废话:

  • explicit constructors
  • deleted constructors

因此,您可以这样做:

class A {
  public :
    int32_t temp ;
    explicit A( bool y = false  ) {
    }
    //Additionally
    A(void*) = delete;
};

定义一个只接受void*作为删除对象的构造函数,当传递指针时,该构造函数的重载解析等级将高于bool构造函数。由于无论何时传递指针,重载解析都会选择它,并且由于它已被删除,因此程序将是病态的。