假设我有一个类A,它有一个子类B。
class A
{
public:
A(){};
}
class B : public A
{
public:
B(int value){ foo = value };
int foo;
}
B是A的子类,具有一个整型属性foo。
现在假设我按照下面这样做:
std::vector<A> mylist;
B myB(5); //Create a new instance of class B
mylist.push_back(myB); //Add b to my vector of A.
现在我想访问mylist中的一个元素,并将其强制转换为类型B并检索'foo'。以下做法是否合法?
B *instance = (B *)&mylist[0];
我在我的项目中尝试过这样做,但是如果我打印出foo的值,它会是不正确的:
std::cout<<instance->foo<<std::endl; // This does not give me 5. It gives me a garbage number.
问题的根源在于我不知道在C++中如何正确地转换非指针。