gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:31:05 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com