如何在 C++ 中使用其方法之一获取派生 class 的名称
How to get the name of derived class using one of its methods in c++
我有这个抽象基础 class,我希望它能够获得从中派生的 class 的名称,无论 class 是什么。我想对用户隐藏这个功能,因为我只是用它来制作日志文件或其他东西的名称。我听说过 typeid
但我无法编译它。我也会满足于能够获取对象的名称,而不是 class.
#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; }
可能有几种方法可以做到这一点...
我可能
1) 在基础 class 中创建一个抽象 属性 (或访问函数),如:
2)然后在derived的构造函数中class,赋名...然后base就可以用了,看到了...
在 typeid 上调用 name()
,如下所示:type_info::name
return typeid(*this).name();
顺便说一句,这确实让 getName()
功能有点多余。
您可以利用预处理器并在 GCC 和 Clang 中使用 __PRETTY_FUNCTION__
或在 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;
}
不幸的是他们 return 完整的方法名称,上面的例子输出
virtual std::__cxx11::string Derived::getName()
如果你需要它,你可以在 Base
中实现一个辅助函数,它将在最后一个 ::
和 space 之间提取一个 class 名称。
std::string getName() override {
return extractClassName(__PRETTY_FUNCTION__);
}
我有这个抽象基础 class,我希望它能够获得从中派生的 class 的名称,无论 class 是什么。我想对用户隐藏这个功能,因为我只是用它来制作日志文件或其他东西的名称。我听说过 typeid
但我无法编译它。我也会满足于能够获取对象的名称,而不是 class.
#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; }
可能有几种方法可以做到这一点...
我可能 1) 在基础 class 中创建一个抽象 属性 (或访问函数),如:
2)然后在derived的构造函数中class,赋名...然后base就可以用了,看到了...
在 typeid 上调用 name()
,如下所示:type_info::name
return typeid(*this).name();
顺便说一句,这确实让 getName()
功能有点多余。
您可以利用预处理器并在 GCC 和 Clang 中使用 __PRETTY_FUNCTION__
或在 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;
}
不幸的是他们 return 完整的方法名称,上面的例子输出
virtual std::__cxx11::string Derived::getName()
如果你需要它,你可以在 Base
中实现一个辅助函数,它将在最后一个 ::
和 space 之间提取一个 class 名称。
std::string getName() override {
return extractClassName(__PRETTY_FUNCTION__);
}