是否可以从类方法中知道对象实例名称/变量名称?例如:
#include <iostream>
using namespace std;
class Foo {
public:
void Print();
};
void Foo::Print() {
// what should be ????????? below ?
// cout << "Instance name = " << ?????????;
}
int main() {
Foo a, b;
a.Print();
b.Print();
return 0;
}
Run Code Online (Sandbox Code Playgroud) 假设我有以下类层次结构:
class Base
{
virtual int GetClassID(){ return 0;};
public:
Base() { SomeSingleton.RegisterThisObject(this->GetClassID());
}
class Derived
{
virtual int GetClassID(){ return 1;};
public:
Derived():Base(){};
}
Run Code Online (Sandbox Code Playgroud)
嗯,这一切都从我的实际情况简化,但这是它的一般要点.
我想避免在每个派生类的构造函数中调用RegisterThisObject,所以我试图将调用移动到基类的构造函数.
是否有任何模式可用于在不使用构造函数中的虚方法的情况下完成此操作?