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

发布于 2024-10-13 13:46:13 字数 635 浏览 6 评论 0原文

我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

漫雪独思 2024-10-20 13:46:13

取消引用的优先级高于成员访问。您可以添加括号 ((*i​​t).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.).

放赐 2024-10-20 13:46:13

尝试 (*i​​t).display() 或简单地 it->display()

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

何以心动 2024-10-20 13:46:13

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

it->display();

或:

(*it).display();

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

it->display();

or:

(*it).display();
三月梨花 2024-10-20 13:46:13

使用Vector,也可以使用经典形式

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

Using Vector, you can also use classic form

for(size_t x = 0; x < room.size(); x++) {
    room[x].display(); //for objects
    //room[x]->display(); //for pointers
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文