为什么自定义类的这种声明是不可接受的
Why is this declaration of a custom class not acceptable?
在我的代码中,我想声明一个自定义类的实例,像这样:
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
};
相关文章:
- C++typeid模板值转换为联合不可接受的转换
- 如何接受可修改和不可修改的参数?
- 如何声明接受字符串、返回void的闭包的类型
- 如何声明一个接受任何大小的 2D 矢量参数?
- 如何声明功能接受rvalue的任意长度阵列
- 如何声明接受转发引用并返回引用或副本的函数模板
- 类简单分数的不可接受的条件表达式
- STD :: Ostream:类是不可接受的[C ]
- Visual Studio C++不接受>>或<<超过初始声明
- 标记C 声明的一种便携式方式,为C 11所接受的弃用
- 需要接受教育:声明"void encrypt(char*, int)"具有不同的异常说明符"
- 声明一个接受预处理器宏的字符
- 为什么使用using声明引入的私有基类中的成员模板不可访问
- CTOR 声明/定义中接受的 const 限定符(LLVM 错误?)
- 如何在 VBA 中声明一个接受 XlfOper (LPXLOPER) 类型参数的函数
- 在 for 循环中声明两个不同的变量,其中一个是不可移动、不可复制的对象
- 在c++中,如何声明一个接受任意对象的向量数组作为协议的函数
- 如何声明一个接受模板类嵌套类的全局友元函数
- 为什么自定义类的这种声明是不可接受的
- 声明一个接受并返回` `流` `的函数有什么用?而不是重载operator<<