C++:: 使用向量迭代器调用类方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4775411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:26:13  来源:igfitidea点击:

C++:: Call class method using vector iterator?

c++vectorclass-method

提问by cpp_noob

I have a class called Room, the Room class has setPrice and display function.

我有一个名为 Room 的类,Room 类具有 setPrice 和 display 功能。

I stored room objects in a vector:

我将房间对象存储在向量中:

room.push_back(Room("r001", 1004, 2, "small"));
room.push_back(Room("r002", 1005, 2, "small"));
room.push_back(Room("r003", 2001, 4, "small"));
room.push_back(Room("r004", 2002, 4, "small"));

In my main function, i create a display function to display all rooms. Here is my code:

在我的主要功能中,我创建了一个显示功能来显示所有房间。这是我的代码:

void displayRoom()
{
    vector<Room>::iterator it;
    for (it = room.begin(); it != room.end(); ++it) {
         *it.display(); // just trying my luck to see if it works
    }
}

But it does not call the Room's display method.

但它不会调用 Room 的显示方法。

How do I call the Room(class)'s display method (no argument) and setPrice(1 argument) method?

如何调用 Room(class) 的显示方法(无参数)和 setPrice(1 参数) 方法?

回答by

Dereferencing has higher priority than member access. You could add parens ((*it).display()), but you should just use the shortcut that was introduced long long ago (in C) for this: it->display().

解除引用比成员访问具有更高的优先级。你可以添加括号((*it).display()),但你应该使用被引入很久很久以前(在C)的快捷方式是:it->display()

Of course the same rule applies for pointers and everything else that can be dereferenced (other iterators, smart pointers, etc.).

当然,同样的规则适用于指针和其他所有可以取消引用的东西(其他迭代器、智能指针等)。

回答by Alexandre C.

Try (*it).display()or simply it->display().

尝试(*it).display()或干脆it->display()

回答by Oliver Charlesworth

Iterators are a bit like pointers. So you want either:

迭代器有点像指针。所以你想要:

it->display();

or:

或者:

(*it).display();

回答by Oliver Charlesworth

Using Vector, you can also use classic form

使用 Vector,您还可以使用经典形式

for(size_t x = 0; x < room.size(); x++) {
    room[x].display(); //for objects
    //room[x]->display(); //for pointers
}