记面试之一次笔试记录

下面的代码运行结果中X是多少

Int x=0;

Int func()

{

  return ++x;

}

Int main()

{

  decltype(func()) y=func();

  cout<<"x now is:"<<x<<endl;

  return 0;

}

这题考察的重点我觉得应该是decltype,这是C++11的内容,相关的释义如下:

  

萃取类型 decltype

decltype实际上有点像auto的反函数,使用auto可以用来声明一个指定类型的变量,而decltype可以通过一个变量(或表达式)得到类型;

#include <vector>
int main() { int x = 5; decltype(x) y = x; //等于 auto y = x; const std::vector<int> v(1); auto a = v[0]; // a has type int decltype(v[1]) b = 1; // b has type const int&, the return type of // std::vector<int>::operator[](size_type) const auto c = 0; // c has type int auto d = c; // d has type int decltype(c) e; // e has type int, the type of the entity named by c decltype((c)) f = c; // f has type int&, because (c) is an lvalue decltype(0) g; // g has type int, because 0 is an rvalue }


所以答案是:x now is 1
我们将上面的函数中的某一部分改为以下内容,通过调试断点发现,decltype中的func()没有被调用,所以,这个关键字只是通过函数声明的时候的返回值,并没有真正的调用这个函数func(),所以才会得出x=1

decltype(func()) y=0;

    y=func();

2.下面两个初始化vector的代码的含义:

  vector<int> v1(10);

  vector<int> v2{10};

 

猜你喜欢

转载自www.cnblogs.com/yuzhiboprogram/p/10087012.html
今日推荐