相关疑难解决方法(0)

C++类构造函数可以知道它的实例名称吗?

是否可以从类方法中知道对象实例名称/变量名称?例如:

#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)

c++ constructor class instance

15
推荐指数
7
解决办法
7002
查看次数

避免在构造函数中使用虚方法

假设我有以下类层次结构:

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,所以我试图将调用移动到基类的构造函数.

是否有任何模式可用于在不使用构造函数中的虚方法的情况下完成此操作?

c++

5
推荐指数
2
解决办法
2002
查看次数

标签 统计

c++ ×2

class ×1

constructor ×1

instance ×1