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/