练习 2.36:关于下面的代码,请指出一个变量的类型以及程序结束时它们各自的值。
#include <iostream>
int main()
{
int a = 3, b = 4;
decltype (a) c = a; // a = 3, c = 3,c是int型
std::cout << c << a << std::endl;
decltype ((b)) d = a; // a = 3, d是一个引用,和a绑定,d = 3
std::cout << d << a << std::endl;
++c;
std::cout << c << std::endl; // c = 4;
++d;
std::cout << d << a << std::endl; // d = 4,a变为4
return 0;
}
练习 2.37:赋值是会产生引用的一类典型表达式,引用的类型就是左值的类型。也就是说,如果i是int,则表达式 i = x的类型是int &。根据这一特点,请指出下面的代码中每一个变量的类型和值。
#include <iostream>
int main()
{
int a = 3, b = 4;
decltype(a) c = a; // c = 3,int型
std::cout << "c = " << c << " " << "a = " << a << std::endl;
decltype(a = b) d = a; // d = 3 int型
std::cout << "d = " << d << " " << "a = " << a << std::endl;
return 0;
}
练习2.38:说明由decltype所指定的类型和由auto指定的类型有何区别。请举出一个例子子,decltype指定的类型与auto指定的类型一样;再举一个例子,decltype指定类型与auto指定的类型不一样。
网上参考答案:
auto关键字根据初始式推断对象的类型:
auto i1 = 12; int
auto & i2 = i1; int &
decltype(a)关键字的推断规则:
1.如果a是一个标识符,则推断结果与标志符的类型一致
2.如果a是一个表达式,并且a的结果是将亡值(std::move),则推断结果位右值
3.如果a是一个表达式,并且a的结果是左值,则推断结果为左值
4.其他情况与a类型一致。
不同
Const int ci=0,&cj=ci;
Decltype(ci) x=0; //x 为const int
Auto x=ci;//x为 int 对顶层const处理不同 相同
int ci=0,&cj=ci;
Decltype(ci) x=0; //x 为 int Auto x=ci;//x为 int
C++变量类型与值详解
本文通过几个具体的C++代码实例,详细解析了变量类型的指定方式,包括decltype与auto的区别,以及不同类型变量的值的变化过程。对于理解C++变量类型和值的设定具有很好的指导意义。
563

被折叠的 条评论
为什么被折叠?



