C++:: 使用向量迭代器调用类方法?
我有一个名为 Room 的类,Room 类有 setPrice 和显示功能。
我将房间对象存储在向量中:
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"));
在我的主函数中,我创建了一个显示函数来显示所有房间。这是我的代码:
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
}
}
但它没有调用 Room 的显示方法。
如何调用 Room(class) 的 display 方法(无参数)和 setPrice(1 argument) 方法?
I have a class called Room, the Room class has setPrice and display function.
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.
How do I call the Room(class)'s display method (no argument) and setPrice(1 argument) method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
取消引用的优先级高于成员访问。您可以添加括号 (
(*it).display()
),但您应该使用很久以前(在 C 中)引入的快捷方式:it->display ()
。当然,同样的规则适用于指针和其他所有可以取消引用的东西(其他迭代器、智能指针等)。
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()
.Of course the same rule applies for pointers and everything else that can be dereferenced (other iterators, smart pointers, etc.).
尝试
(*it).display()
或简单地it->display()
。Try
(*it).display()
or simplyit->display()
.迭代器有点像指针。所以你想要:
或:
Iterators are a bit like pointers. So you want either:
or:
使用Vector,也可以使用经典形式
Using Vector, you can also use classic form