如何初始化对象数组?

Myregm

我已经编写了这段代码,但是在尝试初始化Critter对象数组并且不知道它们的含义时遇到了一些错误

我的代码:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Critter {
private:
    string crName;
public:
    Critter(string = "Poochie");
    string getName() const { return crName; }
};

Critter::Critter(string n) {
    crName = n;
}

int main() {
    Critter c[10] = { "bob","neo","judy","patrik","popo" }; //here
    return 0;
}

错误:

E0415 - no suitable constructor exists to convert from "const char [4]" to "Critter"
...
4 more like this.

该代码适用于朋友的Visual Studio 2017,但不适用于我的2019版本。

谢谢。

dxiv

Critter c[10] = { "bob","neo","judy","patrik","popo" };

定义的数组const char *Critter使用这些字符串初始化一个数组,请执行以下操作:

Critter c[10] = { {"bob"}, {"neo"}, {"judy"}, {"patrik"}, {"popo"} };


[ 编辑 ]有人指出,相同的答案最初是在评论中发布的,只是将其隐藏在外部链接中,没有指示其背后的原因,而在发布上述内容之前我没有看到。感谢@drescherjm,所以我将其留在此处作为CW。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章