如何使用派生类在 c++ 中的方法之一获取派生类的名称

How to get the name of derived class using one of its methods in c++

本文关键字:派生 获取 何使用 c++ 方法      更新时间:2023-10-16

我有这个抽象基类,我希望它能够获得从它派生的类的名称,无论它是什么类。我想对用户隐藏此功能,因为我只是使用它来制作日志文件的名称或其他东西。我听说过typeid但我无法编译它。我也会满足于能够获取对象的名称,而不是类。

#include <typeinfo>
class Base{ 
public:
virtual void lol() = 0;
std::string getName(); 
};
std::string Base::getName() {
return typeid(*this);  // this doesn't work!
}

class Derived : public Base{
void lol() {}; 
};
int main(int argc, char **argv) {
Derived d;
std::cout << d.getName() << "n";
return 0; }

在typeid上调用name(),如下所示:type_info::name

return typeid(*this).name();

顺便说一下,这确实使getName()功能有点多余。

您可以利用预处理器并在 GCC 中使用__PRETTY_FUNCTION__和 Clang,或者在 Visual C++ 中使用__FUNCTION__

#include <iostream>
#include <string>
class Base { 
public:
virtual std::string getName();
};
std::string Base::getName() {
return __PRETTY_FUNCTION__;
}
class Derived : public Base {
public:
std::string getName() override {
return __PRETTY_FUNCTION__;
}
};
int main(int argc, char **argv) {
Derived d;
std::cout << d.getName() << "n";
return 0;
}

不幸的是,它们返回完整的方法名称,上面的示例输出

virtual std::__cxx11::string Derived::getName()

如果需要,您可以在Base中实现一个帮助程序函数,该函数将在最后一个::和空格之间提取类名。

std::string getName() override {
return extractClassName(__PRETTY_FUNCTION__);
}

可能有几种方法可以做到这一点...

我可能会 1( 在基类中创建一个抽象属性(或访问器函数(,如下所示:

2(然后在派生类的构造函数中,分配名称...然后基地可以使用它并看到它...