从指针转换为非标量对象类型?

Rav*_*ikh 3 c++ pointers overloading default-arguments

有人可以解释为什么以下工作,尝试以下代码,它工作正常.

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  ----------
Run Code Online (Sandbox Code Playgroud)

Whi*_*TiM 7

在你的情况下.编译器使用隐式定义的复制/移动分配运算符.首先A使用你的构造函数使用指针构造指针bool.


所有指针类型都可以隐式转换boolC++.有两种方法可以防止这种废话:

  • explicit 建设者
  • deleted 建设者

因此,你可以这样做:

class A {

  public :
    int32_t temp ;
    explicit A( bool y = false  ) {
    }

    //Additionally
    A(void*) = delete;
};
Run Code Online (Sandbox Code Playgroud)

定义一个构造函数只void*为删除,将有重载解析该构造比更高级别bool时,你传递一个指针的构造函数.因为只要你传递一个指针就会被重载决策选中,因为它被删除了,程序就会格式不正确.