Reputation: 67
I've written this code but I have some errors when I try to initialize an array of Critter
objects and don't know what they're about.
My code:
#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;
}
The errors:
E0415 - no suitable constructor exists to convert from "const char [4]" to "Critter"
...
4 more like this.
This code worked on a friend's Visual Studio 2017, but not in mine which is the 2019 version.
Thanks.
Upvotes: 2
Views: 394
Reputation: 23792
The initialization you have is for an array of strings, for the objects you need:
Critter c[10] = {Critter("bob"), Critter("neo"), Critter("judy"),
Critter("patrik"), Critter("popo")};
Or
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.
This second initialization may be what your friend used, and maybe you forgot the braces, the IDE version difference doesn't seem relevant here.
Note that C++ provides a container for fixed size arrays, std::array
:
std::array<Critter, 10> c = {Critter("bob"), Critter("neo"),
Critter("judy"), Critter("patrik"), Critter("popo")};
On a side note:
You should avoid using namespace std;
Upvotes: 10
Reputation: 17628
Critter c[10] = { "bob","neo","judy","patrik","popo" };
This defines an array of const char *
. To initialize an array of Critter
with those strings, instead:
Critter c[10] = { {"bob"}, {"neo"}, {"judy"}, {"patrik"}, {"popo"} };
Upvotes: 4
Reputation: 17454
C++ only allows one "user-defined conversion" at a time.
You're providing char const[N]
s (let's call them char const*
s for the sake of argument), which need to be turned into std::string
s (which count as "user-defined" in this context), which need to be turned into Critter
s.
That's two conversions, not one.
That's just a limitation of C++, I'm afraid. You'll have to temporarily instantiate either strings or Critter
s within that initialiser.
Upvotes: -1
Reputation: 747
string c[10] = {"bob","neo","judy","patrik","popo"};
Would be correct.
{"bob","neo","judy","patrik","popo"}
is an array containing string elements.
You need to do
Critter c[10]={ Critter("bob"),Critter("neo"),Critter("judy"),Critter("patrik"),Critter("popo")};
Upvotes: 0