【问题标题】:How do I send the 'this' pointer to a function not by using 'instance.function()'?如何不使用“instance.function()”将“this”指针发送到函数?
【发布时间】:2021-11-13 17:26:17
【问题描述】:

我可以不使用. 运算符将实例发送到函数吗?

例如:

// header file
class A 
{
public:
    void foo() {std::cout << "Hello" << std::endl;}
};
// main file
A instance = new A;
instance.foo();
// instead do something like this
A::foo(instance);

我可以这样做吗?

【问题讨论】:

  • 您需要将函数更改为 static 并接受 A* 作为参数。你试过这样做吗?
  • 除非它不应该是你的“主文件”中的A* - 不清楚因为你在那个sn-p中有非编译代码
  • 我的问题是,我可以在不使用 .运算符
  • 嗯,你可以写成(instance.*&amp;A::foo)(),那就是运营商.*而不是.,或者如果你真的讨厌经期std::invoke(&amp;A::foo, instance)。但这一切都很愚蠢,那么您实际上想做什么?
  • @reem_mikulsky A instance = new A; instance.foo(); 无法编译。您需要改用A instance; instance.foo();A *instance = new A; instance-&gt;foo(); delete instance;

标签: c++ oop


【解决方案1】:

是的,您可以间接通过std::invoke

#include <functional>
#include <iostream>

struct A {
  void foo() {
    std::cerr << "hi\n";
  }
};

int main() {
  A a;
  std::invoke(&A::foo,a);
}

但是std::invoke 的实现可能在内部只应用.* 运算符。

【讨论】:

    【解决方案2】:

    非常欢迎您使用 pointer to member 语法。

    A instance;
    auto fn = &A::foo;
    (instance.*fn)();
    

    .*. 是不同的运算符。这是否更具可读性留给读者作为练习(提示:不是)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      相关资源
      最近更新 更多