请看一下这段代码:
#include <vector>
#include <iostream>
#include <string>
using namespace std;
class A
{
private:
string contentA;
public:
A(){ contentA = ""; };
A( string setContent ){ contentA = setContent; };
virtual string printContent(){ return contentA; };
};
class B: public A
{
private:
string contentB;
public:
B( string setContent ){ contentB = setContent; };
virtual string printContent(){ return contentB; };
};
int main()
{
vector<A*> aPointer;
vector<B> bVector;
B b1("b1");
//store b1 obj in bVector
bVector.push_back( b1 );
//store the current(last) obj address to aPointer for access later
aPointer.push_back( &bVector.back() );
// B b2("b2");
// bVector.push_back( b2 );
// aPointer.push_back( &bVector.back() );
for( vector<A*>::iterator it = aPointer.begin(); it != aPointer.end(); it++ )
{
cout << (*it)->printContent() << endl;
}
}
aPointer 将存储指向 B 向量元素的指针。
请问为什么在for循环中访问B向量中的第二个元素时会出现分段错误?
我已经输入了十六进制,它会再次正常工作。