为什么自定义类的这种声明是不可接受的

Why is this declaration of a custom class not acceptable?

本文关键字:声明 不可接受 自定义 为什么      更新时间:2023-10-16

在我的代码中,我想声明一个自定义类的实例,像这样:

 MyClass anInstance;
 if(something){
      anInstance = MyClass("instantiated like this");
 }else{
      anInstance = MyClass("not instantiated like that");
 }
 //use my anInstance object
 ...

我的IDE标记了我声明anInstance的第一行,它说:No matching constructor for initialization of 'MyClass'

这有什么违法的吗?

MyClass可能缺少默认构造函数。如果是,则需要在声明它时对其进行初始化。像这样:

MyClass anInstance(something ? "instantiated like this" : "not instantiated like that");

forward声明不足以做任何会导致指针的事情。

如果你需要做任何事情,比如实例化类,你将需要完整的声明。有什么原因不只是拉入包含类的.h文件吗?

为MyClass提供一个构造函数,它接受如下字符串:

MyClass {
   public:
   MyClass(const std::string &s):str(s) {}
};

你只需要做

class MyClass {
  public:
    MyClass() {}
    //other code
};