問題描述
是否也可以獲取對象名稱?
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.
這篇關于如何從 C++ 對象中獲取類名?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!