事先:我是C ++的新手,所以请善待。 ; - )
我试图将几个对象(结果)添加到矢量(结果),但不知怎的,它并没有按照我想要的方式工作。^^
更新:我稍微更改了代码并显示了更多代码以获取更多信息
//file1
class Result{
public:
Result(string rtype, string rname, double rcosts){
type = rtype; name = rname; costs = rcosts;
}
private:
string type, name; double costs;
};
//file2
void getCosts(vector<Parts> parts){
vector<Part *> p;
for(unsigned i = 0; i < parts.size(); i++){
p.push_back(&parts[i]);
}
cout << p.at(0)->getName() << p.at(0)->getPrice << endl; //this output is correct
cout << p.at(0)->getName() << p.at(0)->getPrice << endl; //this output is correct
cout << p.at(0)->getName() << p.at(0)->getPrice << endl; //this output is correct
vector<Result *> r;
for(std::vector<Part *>::iterator ip = p.begin; ip != p.end(); ip++){
addResult((*ip)->getType(), (*ip)->getName(), r, (*ip)->getPrice());
}
sortAndPrintResults(r);
//after this method printed the results into a file the programm ends. so the scope shouldn't matter. (getCosts is only called once)
}
void addResult(string type, string name, vector<Result *> results, double costs){
Result * res = new Result(type, name, costs);
results.push_back(res);
cout << res->getName() << endl; //this prints the name of every object
}
输出应如下:
abc //results.at(0)
def //results.at(1)
ghi //results.at(2)
但相反它:
abc //results.at(0)
def //results.at(0)
ghi //results.at(0)
error: out of range. //results.at(1)
error: out of range. //results.at(2)
我做错了什么?
答案 0 :(得分:2)
问题出在您的调试中。
此代码添加一个,然后预期三个。
void addResult(string type, string name, vector<Result *> results, double costs){
results.push_back(new Result(type, name, costs));
cout << results.at(0)->getName() << endl;
cout << results.at(1)->getName() << endl;
cout << results.at(2)->getName() << endl;
}
您希望在输出前调用addResult
3次。
在这种情况下,您希望将其放在getCosts
中的forloop之后:
void getCosts(vector<Parts *> p){
for(std::vector<Part *>::iterator ip = p.begin; ip != p.end(); ip++){
addResult((*ip)->getType(), (*ip)->getName(), r, (*ip)->getPrice());
}
//Check results here.
}
编辑: 正如CaptainObvlious所提到的那样,你也将向量by-value传递给addResult函数。
添加按值表示在函数中本地创建vector<Result *>
,并且不会连接回您传入的r
变量(因此当你尝试r.at(0)
,里面什么也没有。
修复此问题非常简单,要将函数参数结果链接到r
向量,您需要将其传递给 by-reference ,这就像预先添加类型一样简单与&#39;&amp;&#39;:
void addResult(string type, string name, vector<Result *>& results, double costs)
答案 1 :(得分:0)
我发现代码中有一些错误,请尝试以下操作:
//file1
class Result{
public:
Result(string rtype, string rname, double rcosts){
type = rtype; name = rname; costs = rcosts; //changed to actually assign to member
}
private:
string type, name; double costs;
};
//file2 - you did not show where you got the 'r' parameter from
void getCosts(vector<Parts *> p){
for(std::vector<Part *>::iterator ip = p.begin; ip != p.end(); ip++){
addResult((*ip)->getType(), (*ip)->getName(), r, (*ip)->getPrice());
}
}
void addResult(string type, string name, vector<Result *> & results, double costs){
Result * res = new Result(type, name, costs);
results.push_back(res);
cout << res->getName() << endl;
}