在我从事的项目中,我需要能够访问程序中每个实例的完整类名。我的方法是声明一个基类,所有类都将从该基类派生而来,该基类将具有一种方法,该方法将正确分解给定实例的类的名称。如下所示:
class Base {
public:
std::string *getClassName() {
char *str = (char*) malloc(1024);
size_t size = 1024;
int status;
char *res = abi::__cxa_demangle( typeid(*this).name(), str, &size, &status );
return new std::string(res);
};
class A : public Base { /*...*/ };
class B : public A { /*...*/ };
// ... and so on
问题是,当我getClassName
从类B的实例访问时,它不返回Base::A::B
而是返回Base
,这是从getClassName
声明的位置可见的类。
我发现的唯一解决方案是getClassName
虚拟化并强制每个类都实现它。但这意味着重写总是相同的代码,这是我不想要的。您知道对此有什么优雅的解决方案吗?
您可以只在基类中定义虚拟析构函数:
#include <iostream>
#include <malloc.h>
#include <cxxabi.h>
using namespace std;
class Base {
public:
virtual ~Base() {}
std::string getClassName() {
char *str = (char*) malloc(1024);
size_t size = 1024;
int status;
char *res = abi::__cxa_demangle( typeid(*this).name(), str, &size, &status );
return std::string(res);
}
};
class A : public Base { /*...*/ };
class B : public A { /*...*/ };
int main()
{
A a;
B b;
cout << a.getClassName() << endl;
cout << b.getClassName() << endl;
}
输出:
./test
A
B
顺便说一句,在这种情况下,最好让__cxa_demangle分配内存(并且不要忘记使用:: free(),因为此示例代码存在内存泄漏)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句