c++ - 在 C++ 中,创建一个在调用类的任何其他函数时始终运行的函数

标签 c++ syntax

C++ 有太多我不知道的东西。

有没有什么方法可以在类中创建一个函数,只要调用该类的任何其他函数,它就会始终被调用? (比如让函数附加到函数的第一个执行路径)

我知道这很棘手,但我很好奇。

最佳答案

是的,有一些额外的代码,一些间接和另一个类,并使用 -> 而不是 .运营商。

// The class for which calling any method should call PreMethod first.
class DogImplementation
{
public:
   void PreMethod();
   void Bark();
private:
   DogImplementation(); // constructor private so can only be created via smart-pointer.
   friend class Dog; // can access constructor.
};

// A 'smart-pointer' that wraps a DogImplementation to give you
// more control.
class Dog
{
public:
   DogImplementation* operator -> ()
   {
       _impl.PreMethod();
       return &_impl;
   }
private:
   DogImplementation _impl;
};

// Example usage of the smart pointer. Use -> instead of .
void UseDog()
{
  Dog dog;
  dog->Bark();    // will call DogImplementation::PreMethod, then DogImplementation::Bark
}

嗯.. 大致按照这些思路可以开发成一个解决方案,我认为可以让你做你想做的事。我在那里勾勒出的内容可能无法编译,但只是给你一个起点。

关于c++ - 在 C++ 中,创建一个在调用类的任何其他函数时始终运行的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/518028/

相关文章:

c# - 将锯齿状数组传递给 C# 中的方法

C++ 禁止声明没有类型的 'binaryTreeType'

c++ - 为我的图形数据结构实现 BFS 时出现问题

c++ - 如何使用 QRegExp 从 QString 中获取子字符串?

mysql - 相同的列名,但数据来自其他表

php - 重命名 PHP 内部命令

C++ 如何使函数/变量成为命名空间的局部变量?

c++ - 程序员对优先队列实现的默认选择是什么?

SQL语法新手学生

换行符后带有三个点的 python 字符串...这是什么东西?