C++获取变量的类型和名称

注:本文基于vc编译器。

1.获取类型typeid

1)typeid的基本使用

#include <iostream>
#include <string>
using namespace std;

class A{};
void help(int k) {
    string s1 = "", s2;
    getline(cin, s1);
    istringstream iss(s1);
    cout << "\//" << endl;//\转义
}

string s;
int main()
{
    cout <<"获取类名"<< typeid(A).name() << endl;
    cout << "获取函数类型" << typeid(help).name() << endl;
    cout << "获取变量类型" << typeid(s).name() << endl;
    return 0;
}

2)typeid是一种运行时类型识别(RTTI)

参考自:C++ typeid关键字详解_CHENG Jian的博客-CSDN博客_c++ typeid

根据其运行时类型识别的特点,其可以识别出基类指针所指的派生类对象。

#include <iostream>
#include <string>
using namespace std;

class A{
public:
    virtual void v(){}
};
class B:public A {
public:
    void v() {}
    void v1(){}
};


const int s=1;
int main()
{
    A* a = new B();
    cout << "获取变量类型" << typeid(*a).name() << endl;
    return 0;
}

3)但是直接用typeid打印变量时,const或者引用会被忽略掉

int main()
{
    const int &i = 0;
    cout << "获取变量类型" << typeid(s).name() << endl;
    return 0;
}

 这种情况可以参考:如何在C++中获得完整的类型名称_木头云的博客-CSDN博客_abi::__cxa_demangle

如何在C++中获得完整的类型名称_卡拉CC的博客-CSDN博客_c++ 获取类名称

这个时候需要自己去定义一些复杂的模板函数。

2.读取变量名

参考自:C++ 获取变量名称 & 获取类型的名称_sjhuangx的博客-CSDN博客_c++ 获取变量名

C/C++程序中获取变量的名称_幻想之渔的博客-CSDN博客_c++获取变量名称

本质上是用到了宏的#,#define varName(x) #x 即会将x转换成一个字符串。

#include <iostream>
#include <string>
using namespace std;

#define varName(x) #x

int main()
{
    const string s = "111";
    cout << "获取变量名" << varName(s) << endl;
    cout << "获取变量名" << typeid(varName(s)).name() << endl;
    return 0;
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值