简体   繁体   中英

creating vector with constructor parameter in c++

Im trying to create 2 vectors of 5 objects (Cats) with a constructor parameter (color).

But i cant find the right syntax.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

class Cats{
Cats(string color);

};

Cats::Cats(string color){
cout << "Cat " << color << " created" << endl;
}

int main()
{
  vector<Cats> blacks (5, "black");
  vector<Cats> whites (5, "white");
}

I want the string of each cat with the color i write to the constructor.

You want vector<Cats> blacks(5, Cats("black")); .

Also see Why should I not #include <bits/stdc++.h>?

The compiler will not automatically perform two implicit conversions. Your string literal is a const char* which needs to be converted to std::string and then to Cats before it is the correct type to pass into the vector constructor.

You can help the compiler out by performing one of the conversions explicitly:

// Pass Cats to the vector constructor, compiler implicitly converts string literal to std::string
vector<Cats> blacks(5, Cats("black"));
// Pass std::string, compiler implicitly converts to Cats before calling the vector constructor
vector<Cats> whites(5, std::string("black"));

Alternatively if you're going to be calling code similar to this often, it could be simpler to add a const char* constructor to Cats :

class Cats{
Cats(string color);
Cats(const char* color)
:Cats(std::string(color))
{}
};

Your original code would then work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM