Visual Studio 2017 C++,无法使用 typeid() 获取信息对象,缺少指针?;

Visual Studio 2017 C++, can't use typeid() to take information object, missing pointer?;

这是我第一次 post 在这里 xD。

最近断了几年,开始提醒自己c++领域的知识。之前在C#工作过。

作为练习的一部分,我开始编写生成汽车class的代码,然后输入和写入数据。 但是我遇到了一个问题。作为练习的一部分,我想使用函数 typeid () 编写对象的名称,并找出什么是 hash_code。 但是我有两个错误,我不能做什么。 如何正确声明指针。

#include "pch.h"
#include <iostream>
#include <string>

using namespace std;

class Car {
public:
    string _mark;
    string _model;
    int _year;
    int _course;

    void UploadData()
    {
        cout << "Set values" << endl;
        cin >> _mark;
        cin >> _model;
        cin >> _year;
        cin >> _course;
        cout << "Values uploaded"<<endl;
    }

    void Write()
    {
        cout << typeid(this).name <<" " << typeid(this).hash_code << " " << " mark " << _mark << " model " << _model << " year " << _year << " course " << _course;
    }
};

int main()
{
    Car test1;
    test1.UploadData();
    test1.Write();
}

错误信息:

Severity Code Description Project File Line Suppression State Error C3867 'type_info::name': non-standard syntax; use '&' to create a pointer to member

Severity Code Description Project File Line Suppression State Error C3867 'type_info::hash_code': non-standard syntax; use '&' to create a pointer to member

namehash_code是classstd::typeinfo的成员函数,所以需要使用括号:

cout << typeid(this).name() <<" " << typeid(this).hash_code()
     << " " << " mark " << _mark << " model " << _model << " year " << _year
     << " course " << _course;

不幸的是,您收到的错误消息具有误导性。编译器认为您正在尝试做一些完全不同且更高级的事情。

但请注意 typeid(this) 将与 typeid(Car*) 完全相同。如果您改写 typeid(*this),那将与 typeid(Car) 相同。 typeid 运算符在具有至少一个虚函数的 class 上使用时开始变得更有趣....