也可以得到对象的名称吗?
#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";
}
在那里我可以找到名字,就像
[classname] = A.classname() = one
[objectname] = A.objectname() = A
C++提供了任何机制来实现这一点吗?
发布于 2010-09-06 06:04:45
可以使用预处理器显示变量的名称。例如
#include <iostream>
#define quote(x) #x
class one {};
int main(){
one A;
std::cout<<typeid(A).name()<<"\t"<< quote(A) <<"\n";
return 0;
}
输出
3one A
在我的机器上。#
将令牌更改为字符串,预处理后行为
std::cout<<typeid(A).name()<<"\t"<< "A" <<"\n";
当然,如果你做了类似的事情
void foo(one B){
std::cout<<typeid(B).name()<<"\t"<< quote(B) <<"\n";
}
int main(){
one A;
foo(A);
return 0;
}
你会得到
3one B
因为编译器没有跟踪所有变量的名称。
就像gcc中发生的那样,typeid().name()的结果是错误的类名,以获得[消]直角版的使用
#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<<"\t"<< quote(A) <<"\n";
free(demangled);
return 0;
}
这给了我
one<int, one<double, int> > A
其他编译器可能使用不同的命名方案。
发布于 2010-09-06 05:50:19
使用typeid(class).name
//插图代码,假设所有内容都包括/命名空间等
#include <iostream>
#include <typeinfo>
using namespace std;
struct A{};
int main(){
cout << typeid(A).name();
}
重要的是要记住,这会给出一个实现定义的名称。
据我所知,在运行时无法可靠地获取对象的名称。在你的密码里。
编辑2:
#include <typeinfo>
#include <iostream>
#include <map>
using namespace std;
struct A{
};
struct B{
};
map<const type_info*, string> m;
int main(){
m[&typeid(A)] = "A"; // Registration here
m[&typeid(B)] = "B"; // Registration here
A a;
cout << m[&typeid(a)];
}
发布于 2016-04-22 13:13:30
要获得类名而不损坏内容,可以在构造函数中使用func宏:
class MyClass {
const char* name;
MyClass() {
name = __func__;
}
}
https://stackoverflow.com/questions/3649278
复制相似问题