C++ primer中关于typedef的疑问

假期在家没事干,老家里有本c++ primer,看到typedef关键字

typedef double wages;

typedef wages base,*p;//p是double *的同义词

typedef就是定义一个别名,使复杂的类型名字变得简单明了、易于理解和使用。

后面有一段和指针的使用,我有点没看明白:
WechatIMG20.jpeg

我写了如下程序验证对应的类型:

#include <bits/stdc++.h>

using namespace std;

int main()

{

typedef char *pstring;

const pstring cstr = 0;

const pstring *ps;

cout << typeid(cstr).name() <<endl;

cout << typeid(ps).name() <<endl;

return 0;

}

程序输出:

[root workspace]#./a.out

Pc

PKPc

看网上的解释
名字是编译器规定的。具体到这个上面你可以记成pointer(P) const(K) char(c)

这个类型和书上说的对不上呀?

回答:

c++filt 可以给出 demangle 的结果,不用猜了:

[root workspace]#./a.out | c++filt -t

char*

char* const*

另外,typeid 会忽略顶层的 cv-qualifier (constvolatile),所以 typeid(cstr) 拿到的是 char*, 而不是 char*const。于是应该就可以对上了。

expr.typeid#5:

If the type of the expression or type-id is a cv-qualified type, the result of the typeid expression refers to a std​::​type_­info object representing the cv-unqualified type.


另外,你可以用 std::is_same 来判断类型是否一致:

    cout << std::is_same<decltype(cstr), char*>::value << endl;

cout << std::is_same<decltype(cstr), char*const>::value << endl;

output:

0

1

以上是 C++ primer中关于typedef的疑问 的全部内容, 来源链接: utcz.com/p/193054.html

回到顶部