简体   繁体   English

在C ++中使用构造函数参数创建向量

[英]creating vector with constructor parameter in c++

Im trying to create 2 vectors of 5 objects (Cats) with a constructor parameter (color). 我试图用构造函数参数(颜色)创建5个对象(猫)的2个向量。

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")); 您需要vector<Cats> blacks(5, Cats("black")); .

Also see Why should I not #include <bits/stdc++.h>? 另请参见为什么不#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. 您的字符串文字是const char* ,需要先转换为std::string ,然后再转换为Cats ,然后才能将其转换为vector构造函数的正确类型。

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 : 另外,如果您经常要调用与此类似的代码,则向Cats添加const char*构造const char*可能会更简单:

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

Your original code would then work. 这样您的原始代码就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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