成员函数指针调用复制构造函数?

发布于 2024-08-01 17:40:04 字数 521 浏览 7 评论 0原文

我试图在代码中创建成员函数的查找表,但它似乎试图调用我的复制构造函数,我通过扩展“不可复制”类来阻止它。 我所拥有的类似于以下内容。

enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };

class Foo {
  fun1(Bar b){ ... }
  fun2(Bar b){ ... }
  ...
  void (Foo::*lookup_table[NUM_FUNS])(Bar b);
  Foo(){ 
    lookup_table[FUN1_IDX] = &Foo::fun1;
    lookup_table[FUN2_IDX] = &Foo::fun2;
  }

  void doLookup(int fun_num, Bar b) {
    (this->*lookup_table[fun_num])(b);
  }
};

错误在于“(this->...”行尝试调用不可见的复制构造函数。为什么它要尝试执行此操作,我必须更改什么才能使其不会执行此操作?

I'm trying to create a lookup table of member functions in my code, but it seems to be trying to call my copy constructor, which I've blocked by extending an "uncopyable" class. What I have is something like the following.

enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };

class Foo {
  fun1(Bar b){ ... }
  fun2(Bar b){ ... }
  ...
  void (Foo::*lookup_table[NUM_FUNS])(Bar b);
  Foo(){ 
    lookup_table[FUN1_IDX] = &Foo::fun1;
    lookup_table[FUN2_IDX] = &Foo::fun2;
  }

  void doLookup(int fun_num, Bar b) {
    (this->*lookup_table[fun_num])(b);
  }
};

The error is that the '(this->...' line tries to call the copy constructor, which is not visible. Why is it trying to do this, and what do I have to change so it won't?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

野稚 2024-08-08 17:40:04

使它们成为参考参数。

enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };

class Foo {
  fun1(Bar &b){ ... }
  fun2(Bar &b){ ... }
  ...
  void (Foo::*lookup_table[NUM_FUNS])(Bar &b);
  Foo(){ 
    lookup_table[FUN1_IDX] = &Foo::fun1;
    lookup_table[FUN2_IDX] = &Foo::fun2;
  }

  void doLookup(int fun_num, Bar &b) {
    (this->*lookup_table[fun_num])(b);
  }
};

在 C++ 中,否则这样的普通参数不仅仅引用对象,而且它们就是这些对象本身。 让它们成为引用参数只会引用传递的内容。 在这个问题上,C++ 与 C 具有相同的语义(在 C 中您将使用指针)。

Make them reference parameters.

enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };

class Foo {
  fun1(Bar &b){ ... }
  fun2(Bar &b){ ... }
  ...
  void (Foo::*lookup_table[NUM_FUNS])(Bar &b);
  Foo(){ 
    lookup_table[FUN1_IDX] = &Foo::fun1;
    lookup_table[FUN2_IDX] = &Foo::fun2;
  }

  void doLookup(int fun_num, Bar &b) {
    (this->*lookup_table[fun_num])(b);
  }
};

In C++, otherwise such plain parameters don't just reference objects, but they are those objects themselves. Making them reference parameters will merely reference what is passed. In this matter, C++ has the same semantics as C (in which you would use pointers for that).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文