我对 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;
}
我通过替换 with 的每个实例解决了我的问题this->getList()
(在 for 循环定义中this->list
有 3 个;一个 in和两个)。为什么使用成员本身而不是通过方法访问它会影响该程序的工作?B::addA(A*)
B::as_a_string()