如何从 C++ 对象中获取类名?

2021-12-09 00:00:00 class c++

是否也可以获取对象名称?

Is it possible to get the object name too?

#include<cstdio>

class one {
public:
    int no_of_students;
    one() { no_of_students = 0; }
    void new_admission() { no_of_students++; }
};

int main() {
    one A;
    for(int i = 0; i < 99; i++) {
        A.new_admission();
    }
    cout<<"class"<<[classname]<<" "<<[objectname]<<"has "
        <<A.no_of_students<<" students";
}

我可以在哪里获取名字,比如

where I can fetch the names, something like

[classname] = A.classname() = one
[objectname] = A.objectname() = A

C++ 是否提供任何机制来实现这一点?

推荐答案

您可以使用预处理器来显示变量的名称.例如

You can display the name of a variable by using the preprocessor. For instance

#include <iostream>
#define quote(x) #x
class one {};
int main(){
    one A;
    std::cout<<typeid(A).name()<<"	"<< quote(A) <<"
";
    return 0;
}

输出

3one    A

在我的机器上.# 将一个token变成一个字符串,经过预处理后的行是

on my machine. The # changes a token into a string, after preprocessing the line is

std::cout<<typeid(A).name()<<"	"<< "A" <<"
";

当然如果你做类似的事情

Of course if you do something like

void foo(one B){
    std::cout<<typeid(B).name()<<"	"<< quote(B) <<"
";
}
int main(){
    one A;
    foo(A);
    return 0;
}

你会得到

3one B

因为编译器不会跟踪所有变量的名称.

as the compiler doesn't keep track of all of the variable's names.

在 gcc 中,typeid().name() 的结果是经过修改的类名,以获得 破解版 使用

As it happens in gcc the result of typeid().name() is the mangled class name, to get the demangled version use

#include <iostream>
#include <cxxabi.h>
#define quote(x) #x
template <typename foo,typename bar> class one{ };
int main(){
    one<int,one<double, int> > A;
    int status;
    char * demangled = abi::__cxa_demangle(typeid(A).name(),0,0,&status);
    std::cout<<demangled<<"	"<< quote(A) <<"
";
    free(demangled);
    return 0;
}

这给了我

one<int, one<double, int> > A

其他编译器可能使用不同的命名方案.

Other compilers may use different naming schemes.

相关文章