简体   繁体   English

C ++,矢量对象

[英]C++, Objects on vector

I wanna store objects on vectors. 我想将对象存储在向量上。 But I do not know why it does not work. 但是我不知道为什么它不起作用。

‪#‎include‬ <iostream>
#include <vector>
using namespace std;

I have a Persona class in the Persona.h file. 我在Persona.h文件中有一个Persona类。 And it only has two method: The default constructor and a method called mensaje(), both are public and it does not have any private member. 它只有两个方法:默认构造函数和一个称为mensaje()的方法都是公开的,并且没有任何私有成员。

#include "Persona.h"

int main()
{
    vector<Persona> personas;
    Persona persona1;
    Persona persona2;

    personas.push_back(persona1);
    personas.push_back(persona2);

    vector<Persona>::const_iterator p;

    for(p = personas.begin(); p <= personas.end(); p++) {

Here is where I get the error message 这是我收到错误消息的地方

        p.mensaje();
    }
}

I think problem is the way that I am trying to call 'p'. 我认为问题在于我试图称呼“ p”的方式。 Is right that I try to use const_iterator instead of any other type? 我尝试使用const_iterator而不是其他任何类型是对的吗?

p is iterator not object itself, you need to dereference it: p是迭代器而不是对象本身,您需要取消引用它:

(*p).mensaje();

OR 要么

p->mensaje();

And

update: 更新:

for(p = personas.begin(); p <= personas.end(); p++) {

to: 至:

for(p = personas.begin(); p != personas.end(); p++) {
                          ^^^^^^

You are trying to call a non-const method on a const object (the object referenced by a const iterator). 您试图在const对象(由const迭代器引用的对象)上调用非const方法。 Since the mensaje() method does not modify the object, it should be declared const, like so: 由于mensaje()方法不会修改对象,因此应将其声明为const,如下所示:

void Persona::mensaje() const;

After you make this change, you should be able to call the method on the const object (reference) returned from the const iterator. 进行此更改之后,您应该能够在const迭代器返回的const对象(引用)上调用方法。

(...in addition to the other syntax errors mentioned in other answers.) (...除了其他答案中提到的其他语法错误。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM