c++ 如何在编译时获取类名?[复制]

ttvkxqim  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(98)

此问题在此处已有答案

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()中调用该函数,但这不是我想要。我想尝试在创建和析构时显示类名

yftpprvb

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工作一样好,是跨平台兼容的,甚至更少的类型。
这是否达到了你想要的?

#include <cmath>
#include <iostream>
#include <string>

class People{
public:
    std::string name;
    int age;
    bool educated;
    People(){
        std::cout << typeid(*this).name() << "class people is initialised\n";
    }
    ~People(){
        std::cout << typeid(*this).name()  << "class people is destroyed\n";
    }
private:
    double worth;
};

int main(){
    People Joe;
}

字符串
回应评论:

People(std::string const& str)
: name(str)
{
        std::cout << name << " class people is initialised\n";
    
}

////

int main(){
    Person Joe("Joe");
}


请注意这个重要的区别:People(std::string str)将创建字符串的副本(这通常是昂贵的)。
People(std::string const& str)将创建一个常量引用。常量意味着它不能被改变,因为它是一个引用,所以它不会被复制到这里(尽管它会被复制到类成员中)。

相关问题