我有一些对象结构看起来像这样:访问子结构值
struct Object {
string type;
Color c;
float ambient, diffuse;
};
struct Sphere: Object {
Point center;
float radius;
};
struct Square: Object {
Point loc;
float len;
};
而且我有一个充满球和广场结构向量:
vector<Object> objs;
Sphere sp = //sphere stuff
Square sq = //square stuff
objs.push_back(sp);
objs.push_back(sq);
我可以访问父结构中的值就好了,但我很难弄清楚如何访问Sphere和Square结构中的值。这就是我现在正在做的:
cout << objs.at(i).type << endl; //This works
cout << objs.at(i).center.x << endl; //Not working
有谁知道如何做到这一点?
首先[read about object slicing](http://stackoverflow.com/questions/274626/what-is-object-slicing)。然后学习更多关于*指针*的知识。最后关于[upcasting和(更具体地)*** downcasting ***](https://www.tutorialcup.com/cplusplus/upcasting-downcasting.htm)以及如何使用['dynamic_cast'](http:///en.cppreference.com/w/cpp/language/dynamic_cast)。那么你应该知道如何解决你的问题。 –