[英]Accessing Base class protected data member vector in derived class give error 139
It may have been answered somewhere, but I could not find the correct words to search.它可能在某处得到了回答,但我找不到要搜索的正确词。
I have base class我有基类
class B
{
protected:
std::vector<int> v;
public:
B(): v{} {}
void test()
{
v.push_back( 10 );
std::cout << v[0] << std::endl; // prints 10
}
};
child class儿童班
class C: public B
{
public:
C() {}
void print() { std::cout << v[0] << std::endl; } // error here
};
main function主功能
int main()
{
B b;
b.test(); // initialized vector 10
C c;
c.print(); // error 139 here
return 0;
}
If I initialize vector in base constructor no error.如果我在基本构造函数中初始化向量没有错误。
B(): v{ 10 } {}
I cannot figure out why?我不明白为什么? I may doing something really stupid, - assist me on error, I really appreciate it.
我可能会做一些非常愚蠢的事情, - 帮助我解决错误,我真的很感激。
b
and c
are different instances and the vector v
doesn't have any elements by default. b
和c
是不同的实例,向量v
默认没有任何元素。 Reading v[0]
in this state is reading out-of-range and will cause error.在这种状态下读取
v[0]
是读取超出范围并且会导致错误。
The B::test()
function pushes something to the vector, so calling it will eliminate this error. B::test()
函数将某些内容推送到向量,因此调用它可以消除此错误。
int main()
{
B b;
b.test(); // initialized vector 10
C c;
c.test(); // call this to have v in c have something
c.print(); // error 139 hear
return 0;
}
The error is simply an out-of-bounds violation, and therefore undefined behavior.该错误只是越界违规,因此是未定义的行为。 After this line
这条线之后
C c;
The vector cv
is empty.向量
cv
为空。 Therefore std::cout << v[0]
tries to access an element that doesn't exist.因此
std::cout << v[0]
尝试访问不存在的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.