访问 vector 中的子结构体值
Access child struct values in vector
我有一些 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
中存储Square
或Sphere
,你只是存储Object
s。您应该阅读什么是对象切片?。
也就是说,如果要改为存储指向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
(这些是解释的链接)。
相关文章:
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 使用std::copy将一个结构体的数组转换为另一个结构的Vector
- Vector::erase()也擦除结构体的成员向量
- 从std::vector存储到std::set,其中vector包含一个结构体,而std::set只包含该结构体中的一个
- 结构体的vector.size()将返回什么
- 在结构体中初始化vector
- 将vector中结构体的成员字符串打印到cout流
- 从映射文件中读取带有vector的结构体
- 使用已定义结构体的vector到达未初始化内存
- 我的std::vector是否包含指针或结构体?
- 将结构体复制到vector
- 将带有字符串成员的结构体对象压入std::vector时出错
- 在c++和c#之间传递vector结构体
- 将vector结构体写入文件
- 传递一个成员为vector的结构体
- 具有vector成员的全局结构体
- 向Std::vector添加结构体时使用Std::bad_alloc