class A
{
public:
string name;
float length;
float weight;
bool isEnabled;
};
当我在这个类的向量上做push_back()
时,它第一次起作用,但不会在随后的push_back()
次调用中起作用。可能是因为字符串成员?如果是这样,为什么?
答案 0 :(得分:1)
我试用了你的代码。
vector<Aclass> aClass;
aClass.push_back(Aclass("John Doe ", 6.2 , 220 , true) );
aClass.push_back(Aclass("John Doe2 ", 6.2 , 220 , true) );
aClass.push_back(Aclass("John Doe3 ", 6.2 , 220 , true) );
aClass.push_back(Aclass("John Doe4 ", 6.2 , 220 , true) );
但无法复制您的错误。
这段代码推回了四次。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Aclass
{
public:
string name;
double length;
double weight;
bool isEnabled;
Aclass(){}
~Aclass(){}
Aclass(string _name, double _length, double _weight, bool _isEnabled ) //constructor
{
name = _name;
length = _length;
weight = _weight;
isEnabled = _isEnabled;
cout<<" \n";
cout<<"Name : "<<name<<" \n";
cout<<"length : "<<length<<" \n";
cout<<"weight : "<<weight<<" \n";
cout<<" \n";
}
};
int main()
{
vector<Aclass> aClass;
aClass.push_back(Aclass("John Doe ", 6.2 , 220 , true) );
aClass.push_back(Aclass("John Doe2 ", 6.2 , 220 , true) );
aClass.push_back(Aclass("John Doe3 ", 6.2 , 220 , true) );
aClass.push_back(Aclass("John Doe4 ", 6.2 , 220 , true) );
cout<<" \n";
return 0;
}
输出:
Name : John Doe
length : 6.2
weight : 220
Name : John Doe2
length : 6.2
weight : 220
Name : John Doe3
length : 6.2
weight : 220
Name : John Doe4
length : 6.2
weight : 220
Press any key to continue
答案 1 :(得分:-3)
为什么string
与它有关?
你做过#include <string>
吗?
您没有提到您的class
是否有复制构造函数。
它是这样的:
class A {
public:
A() //default constructor
A(const A&) //copy constructor
};
默认情况下,c ++将复制所有公共成员,但您需要有一个复制构造函数才能使用STL容器和push_back()