访问 vector 中的子结构体值

Access child struct values in vector

本文关键字:结构体 vector 访问      更新时间:2023-10-16

我有一些 Object 结构看起来像这样:

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

有谁知道如何做到这一点?

你不能,它们不再存在了。你不是在vector中存储SquareSphere,你只是存储Objects。您应该阅读什么是对象切片?。

也就是说,如果要改为存储指向Object指针std::vector<Object*>可以将指针传递给派生类型的对象。但是,您如何知道vector中的哪个元素是Square,哪个是Sphere.拥有基类的全部目的是通过virtual函数为所需的功能提供一个接口,派生类以不同的方式实现该接口:

struct Base {
virtual void foo() { std::cout << "foo in basen"; }
};
struct Derived1 : Base {
void foo() override { std::cout << "foo in Derived1n"; }
};
struct Derived2 : Base {
void foo() override { std::cout << "foo in Derived2n"; }
};
Derived2 d;
Base* b = &d;
b->foo(); // prints "foo in Derived2n"

也就是说,要从Object*获取Square*,如果您确定它是Square,请使用static_cast<Square*>(objP),如果您不确定,请使用dynamic_cast<Square*>(objP)(如果您错了,它将返回空指针)。不过,必须这样做可能表明设计不佳!


另外,请重新考虑您对通常被认为是不良做法的使用:using namespace std;endl(这些是解释的链接)。