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