此问题在此处已有答案:
How can I get the class name from a C++ object?(10个答案)
去年关闭。
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
class People{
public:
string name;
int age;
bool educated;
People(){
cout << [name] << "class people is initialised" << endl;
}
~People(){
cout << [name] << "class people is destroyed" << endl;
}
private:
double worth;
};
int main(){
People Joe;
}
如何在构造函数和析构函数中显示类名?我看到另一个方法在main()中调用该函数,但这不是我想要。我想尝试在创建和析构时显示类名
1条答案
按热度按时间yftpprvb1#
我可以自由地修复代码中的一些小问题:
<cmath>
是正确的C头文件,使用它代替<math.h>
(C头文件。C和C是不同的)。不要养成使用
using namespace std
的早期习惯。是的,它看起来很方便,但是read here why you should not do it.使用
std::endl
可能会降低你的性能。Read here about the differences。使用\n
工作一样好,是跨平台兼容的,甚至更少的类型。这是否达到了你想要的?
字符串
回应评论:
型
请注意这个重要的区别:
People(std::string str)
将创建字符串的副本(这通常是昂贵的)。People(std::string const& str)
将创建一个常量引用。常量意味着它不能被改变,因为它是一个引用,所以它不会被复制到这里(尽管它会被复制到类成员中)。