在 C++ 中是否可以这样调用对象方法?
这是我的类定义:
class A {
public:
void do_lengthy_work() {
cout << "working." << endl;
}
};
我有一个 A
类型的对象,我想对其调用 do_lengthy_work()
:
A a;
a.do_lengthy_work();
是否也可以使用某种变体调用相同的方法以下的?
A::do_lengthy_work(a);
Here's my class definition:
class A {
public:
void do_lengthy_work() {
cout << "working." << endl;
}
};
I have an object of type A
, and I want to call do_lengthy_work()
on it:
A a;
a.do_lengthy_work();
Is it also possible to call the same method using some variant of the following?
A::do_lengthy_work(a);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以这样做。
You could do this.
按照你写的方式,不,你不能这样做。您可以创建静态重载,尽管我建议不要这样做:
但是,这可能会令人困惑。你为什么要这样做?为什么不能直接调用
a.do_lengthy_work()
?The way you wrote it, no you can't do that. You could create a static overload, although I would advise against this:
However, this can be confusing. Why do you want to do this? Why can't you just call
a.do_lengthy_work()
?是的,如果该方法被声明为
静态
,则意味着它不属于该类的特定实例。Yes, if the method is declared to be
static
, meaning it does not belong to a particular instance of the class.您可以使用
mem_fun_ref
包装该函数:这对于像
for_each
这样的 STL 算法非常有用:如果您有一个
A *
,您可以使用mem_fun
:You can wrap the function with
mem_fun_ref
:This can be very useful for STL algorithms like
for_each
:If you have an
A *
, you would usemem_fun
: