【发布时间】:2013-08-13 23:46:53
【问题描述】:
我对 C++ 有点陌生,我有一个很好奇的问题。有一段时间我遇到了分段错误,虽然我最终让它工作了,但我想知道为什么以前没有。这就是我所拥有的:
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
class A {
private:
int num;
public:
A(int i){this->num=i;}
int getNum(){return this->num;}
};
class B {
private:
vector<A*> list;
public:
vector<A*> getList(){return this->list;}
void addA(A* i){this->getList().push_back(i);}
string as_a_string(){
stringstream result;
cout << "Flag1" <<endl; //only for debug, this prints
for (vector<A*>::iterator x = this->getList().begin(); x != this->getList().end(); ++x) {
cout << "Flag2" << endl; //only for debug, this prints
A* w = *x;
cout << "Flag3" << endl; //only for debug, this prints
result << w->getNum() << " ";
cout << "Flag4" << endl; //only for debug, this does not print
}
return result.str();
}
};
int main() {
A* a = new A(4);
B* b = new B();
b->addA(a);
cout << b->as_a_string() << endl;
return 0;
}
我通过用this->list 替换this->getList() 的每个实例解决了我的问题(有3 个;一个在B::addA(A*) 中,两个在B::as_a_string() 的for 循环定义中)。为什么使用成员本身而不是通过方法访问它会影响该程序的工作?
【问题讨论】:
-
getList()按值返回。每次调用它都会得到B::list的副本。 -
我曾想过,但我不知道如何让它返回一个参考(我认为这是正确的术语,无论如何),这会让它按照我的想法行事它应该表现。我该如何正确地做到这一点?
标签: c++ class vector segmentation-fault