这是可能的。如果你的编译支持__PRETTY_FUNCTION__
或__func__
(见this),那么你可以这样做:
#include <iostream>
using namespace std;
class FileTwo{
public:
FileTwo(){
cerr<<"constructor for "<< __PRETTY_FUNCTION__ <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< __PRETTY_FUNCTION__ <<" at "<<&(*this)<<endl;
}
};
int main(){
FileTwo two;
return 0;
}
请注意,我也印到cerr
以确保此输出被立即刷新,如果程序不丢失崩溃。另外,由于每个对象都有唯一的指针,因此我们可以使用它来查看特定对象何时被制造或被杀死。
用于我的计算机上的上述程序的输出是:
constructor for FileTwo::FileTwo() at 0x7fff641cde40
Destructor for FileTwo::FileTwo() at 0x7fff641cde40
注意__func__
是C99标准标识符。 C++ 0x以“实现定义的字符串”的形式添加了支持。
__FUNCTION__
是某些编译器(包括Visual C++(请参阅documentation)和gcc(请参阅documentation))支持的预标准扩展。
__PRETTY_FUNCION__
是一个海湾合作委员会的扩展,它做同样的东西,但更漂亮。
This question有关于这些标识符的更多信息。
根据您的编译器,这可能会返回类的名称,尽管它可能有点损坏。
#include <iostream>
#include <typeinfo>
using namespace std;
class FileTwo{
public:
FileTwo(){
cerr<<"constructor for "<< typeid(*this).name() <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< typeid(*this).name() <<" at "<<&(*this)<<endl;
}
};
int main(){
FileTwo two;
return 0;
}
如果你试图去哪个类被实例变量的名称(two
你的情况),那么就没有,就我所知,一个办法做到这一点。以下将模拟它:
#include <iostream>
#include <string>
using namespace std;
class FileTwo{
public:
FileTwo(const std::string &myName) : myName(myName) {
cerr<<"constructor for "<< myName <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< myName <<" at "<<&(*this)<<endl;
}
private:
std::string myName;
};
int main(){
FileTwo two("two");
return 0;
}
你是什么意思的“名称”?变量的标识符?像'foo(FileTwo());'这样的代码中的“名称”是什么? – Angew
你不能。C++不支持反射。 – zapredelom
@zapredelom反射与它无关。对象在C++中没有名称,句号。没有任何反射会解决这个问题。另一方面,C++确实有RTTI,它将提供类型信息。 – EJP