如何使用派生类在 c++ 中的方法之一获取派生类的名称
How to get the name of derived class using one of its methods in c++
我有这个抽象基类,我希望它能够获得从它派生的类的名称,无论它是什么类。我想对用户隐藏此功能,因为我只是使用它来制作日志文件的名称或其他东西。我听说过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(然后在派生类的构造函数中,分配名称...然后基地可以使用它并看到它...
相关文章:
- 派生类如何获取基的成员?
- 如何在新的派生对象中获取基本对象的数据?
- 获取我的基类以递增派生类对象整数
- 从组件的 std::type_index 获取派生最多的类型
- C++ 如何使派生类自动获取基类参数
- 获取指向派生类的指针在 C++ 中以运行时异常结束
- 通过基类指针获取派生类对象的引用
- 如何使用派生类在 c++ 中的方法之一获取派生类的名称
- 不能从派生类中获取基类的成员. C++
- 从派生类 c++ 中获取变量
- 获取派生模板实例化的运行时类型
- 从基类对象的向量中获取特定派生类的对象
- (重复)C++类集/从基类和派生类获取
- 如何在 C++ 中从派生类中获取值
- 如果不在派生类实现中执行此操作,"basic_streambuf"是否会创建自己的获取/放置区域?
- 获取具有基类函数的派生类
- 从基类指针获取模板派生类的值
- 在C++中,是否允许将函数指针强制转换为将指向基类或派生类的指针作为参数获取的函数指针
- 为什么基类型指针不能获取派生类对象的地址值?
- 当可能的许多派生类型时,从基本类型的实例中获取派生类型