在C++中,仿函数可以是另一个类的静态成员吗? [重复]

问题描述 投票:0回答:0

出于各种原因,我想制作一个仿函数,它是另一个类的静态成员。但是,这有时会导致链接器错误。这不合法吗?如果是这样,为什么不呢?

这是一个最小的例子。

#include <iostream>

struct {
  int operator() (int x) {return x*x;} 
} standaloneFunctor;

struct Thing {
  struct {           int operator() (int x) {return x*x;}   } memberFunctor;
  static struct {    int operator() (int x) {return x*x;}   } staticFunctor;
};

int main () {
  
  std::cout << standaloneFunctor(3) << '\n';   // call the stand-alone functor
  
  Thing thing;
  std::cout << thing.memberFunctor(3) << '\n';  // call functor that is member of class
  
  std::cout << Thing::staticFunctor(3) << '\n'; // call functor that is static member of class
  return 0;
}

使用-O0 编译和链接会导致链接器错误:

yloh$ g++ a.cc -O0 -o a ; ./a
/usr/bin/ld: /tmp/ccd6rdI7.o: in function `main':
a.cc:(.text+0x8e): undefined reference to `Thing::staticFunctor'
collect2: error: ld returned 1 exit status
bash: ./a: No such file or directory

在这种情况下使用 -O3 进行编译和链接会产生预期的结果(但对于更复杂的程序会失败):

yloh$ g++ a.cc -O3 -o a ; ./a
9
9
9

编译器版本为g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0。谁能解释导致链接器错误的原因,并提出解决方法? [大概一种解决方法是定义一个虚拟对象并调用作为其数据成员的仿函数,但这听起来很老套。]提前致谢!

c++ class static linker functor
© www.soinside.com 2019 - 2024. All rights reserved.