c++ - 如何初始化对象数组?

标签 c++ arrays visual-studio runtime-error object-initialization

我已经编写了这段代码,但是当我尝试初始化一个 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.

此代码适用于 friend 的 Visual Studio 2017,但不适用于我的 2019 版本。

谢谢。

最佳答案

您拥有的初始化是针对字符串数组,针对您需要的对象:

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

或者

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

*This second method is credited to @drescherjm comment followed by @dxiv's answer, both mentioned it first.

这第二次初始化可能是你 friend 用的,也可能你忘记了大括号,IDE版本差异在这里似乎无关紧要。

请注意,C++ 为固定大小的数组提供容器,std::array :

std::array<Critter, 10> c = {Critter("bob"), Critter("neo"),
                             Critter("judy"), Critter("patrik"), Critter("popo")};

旁注:

You should avoid using namespace std;

关于c++ - 如何初始化对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62394106/

相关文章:

c++ - 复制构造函数调用 boost::multi_index_container 中的自定义排序谓词

c - 当您写入内存超出数组范围时会发生什么?

windows - 如何删除 Windows 静态库中导出的符号?

c# - vsto : c# change localization of Excel UI objects, 例如功能区,在运行时

css - Visual Studio 2012 中查找特定 id 或类的 css 的最有效方法是什么

c++ - 在 Linux Mint 上使用多个版本的 libboost

c++ - 在 C++ 中如何处理接近于零的值?

c++ - 列表初始化的 char 数组是否仍然以 null 结尾?

arrays - 在汇编中声明和索引 qword 整数数组

c - 如何使用指针从二维字符数组中生成句子