在c ++中创建一个总是在调用类的任何其他函数时运行的函数

fms*_*msf 3 c++ syntax

C++有很多我不知道的东西.

有没有办法在类中创建一个函数,只要调用该类的任何其他函数,它就会被调用?(比如使函数自身附加到函数的第一个执行路径)

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

Sco*_*ham 14

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

// 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
}
Run Code Online (Sandbox Code Playgroud)

那么......大致沿着这些方向的东西可以发展成一个我认为可以让你做你想做的解决方案.我在那里描绘的内容可能无法编译,但只是为了给你一个起点.


Chr*_*isW 9

是.:-)

  • 将对象包装在智能指针中
  • 从智能指针的解除引用操作符自动调用对象的特殊功能(以便在客户端解除引用智能指针时调用特殊功能).