【问题标题】:C++ how to add destructor to anonymous class? [duplicate]C ++如何向匿名类添加析构函数? [复制]
【发布时间】:2022-02-09 19:56:32
【问题描述】:

如何在 C++ 中向匿名类添加析构函数?就像在 PHP 中一样,如果我想在我的课程超出范围时运行某些东西,那就是

$foo = new class() {
        public $i=0;
        public function __destruct()
        {
            echo "foo is going out of scope!\n";
        }
    };

但是在具有普通非匿名类的 C++ 中,您可以使用 ~ClassName(){} 指定析构函数,但匿名类没有名称!那么如何将析构函数添加到

class {public: int i=0; } foo;

在 C++ 中?我尝试使用变量名作为类名,但这不起作用:

class {
public:
  int i;
  ~foo(){std::cout << "foo is going out of scope!" << std::endl;}
} foo;

导致

prog.cc: In function 'int main()':
prog.cc:51:31: error: expected class-name before '(' token
   51 |     class {public: int i=0; ~foo(){std::cout << "foo is going out of scope!" << std::endl;};} foo;
      |                               ^

我也尝试只指定~,但这也没有用,

class {
public:
  int i=0;
  ~(){std::cout << "foo is going out of scope" << std::endl;}
} foo;

导致

prog.cc:48:30: error: expected class-name before '(' token
   48 |     class {public: int i=0; ~(){std::cout << "foo is going out of scope" << std::endl;};} foo;
      |                              ^

【问题讨论】:

标签: c++ destructor anonymous-class


【解决方案1】:

这不能在 C++ 中完成。然而,匿名类的真正 C++ 类似物称为匿名命名空间:

namespace {
   struct foo {
     // ... whatever
     ~foo();
   };
}

// ... later in the same C++ source.

foo bar;

现在您可以在此特定 C++ 源文件中的任何位置使用和引用 foos。其他 C++ 源文件可能有自己的匿名命名空间和自己的 foos,而不会产生冲突。最终结果与 C 风格的匿名结构(也称为类)几乎相同,只是它们并不是真正的匿名,只有它们的命名空间是。

【讨论】:

  • 我认为这只是访问全局命名空间的方法:o
  • @hanshenrik Unnamed namespaces
  • 您不需要将一次性使用的类放在命名空间中。你也可以有函数局部类。它们仍然必须有一个名称来定义析构函数,并且您必须内联实现所有函数。
猜你喜欢
  • 2013-06-01
  • 2014-03-20
  • 2011-03-31
  • 2011-11-30
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多