为什么自定义类的这种声明不可接受?
在我的代码中,我想像这样声明我的自定义类的实例:
MyClass anInstance;
if(something){
anInstance = MyClass("instantiated like this");
}else{
anInstance = MyClass("not instantiated like that");
}
//use my anInstance object
...
我的 IDE 标记了我声明 anInstance
的第一行,它说:没有用于初始化“MyClass”的匹配构造函数
这有什么违法的吗?
In my code I want to declare an instance of my custom class like this:
MyClass anInstance;
if(something){
anInstance = MyClass("instantiated like this");
}else{
anInstance = MyClass("not instantiated like that");
}
//use my anInstance object
...
My IDE is flagging the first line where I declare anInstance
, it says: No matching constructor for initialization of 'MyClass'
Is there something illegal about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
MyClass
可能缺少默认构造函数。如果是这样,则需要在声明时对其进行初始化。像这样的事情:MyClass
probably lacks a default constructor. If so, you need to initialize it when you declare it. Something like this:前向声明不足以执行任何会导致指针的操作。
如果您需要执行诸如实例化类之类的操作,您将需要完整的声明。您是否有任何原因不直接提取包含该类的 .h 文件?
The forward declaration is not sufficient to do anything else that what would result in a pointer.
If you need to do anything like instantiating the class you will need the full declaration. Is there any reasons why you are not just pulling in the .h files that contain the class?
为 MyClass 提供一个构造函数,它采用如下字符串文字:
Provide a constructor for MyClass that takes a string literal like this:
你只需要做
You just need to do