C++ 天坑收集
如果有人把以下代码拿去面试笔试其他人,我跟他拼命!!!
用这些代码面试其他人的人,说明这个人不会面试。
1. 寻找下面代码出现的问题
1 //来自 https://www.zhihu.com/question/310052411/answer/2209276153 2 #include3 #include 4 #include 5 6 using namespace std; 7 8 int main() 9 { 10 vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>()); 11 int a = vec.size(); 12 }
说真的,我看了许久也没看出问题,就算我将这部分代码复制到我本地的vs2012中。
后来我换了一种写法:
1 #include2 #include 3 #include 4 5 //using namespace std; 6 7 int main() 8 { 9 std::vector<int> vec(std::istream_iterator<int>(std::cin), std::istream_iterator<int>()); 10 int a = vec.size(); // boom 11 }
编译器告诉我:
error C2751: “std::cin”: 无法限定函数参数的名称
哦吼吼吼吼吼吼吼吼!原来 std::cin 是函数参数名!
那么,std::istream_iterator
vec 是函数名!
std::vector
std::vector
……
再换一种写法:
1 #include2 #include 3 #include 4 5 //using namespace std; 6 7 int main() 8 { 9 std::vector<int> vec(int(cin), int()); 10 int a = vec.size(); 11 }
没错,它就是长这个样子的……
原因在于,函数参数名是可以被括号括住的……
2. 解释以下代码的含义
1 void(*func(void(*)(int)))(int) 2 { 3 }
这个问题我在 中写过了,实际上就是参数和返回值都是函数指针的函数。
3. 分别判断变量 a 与 b 的类型
1 //c++17 2 auto a = {1}; 3 auto b{1};
a: std::initializer_list
b: int
4. 以下代码输出什么 (vs2019, c++17)
1 const int a = 123; 2 int& b = const_cast<int&>(a); 3 b = 456; 4 5 std::cout << a << ", " << b << std::endl;
输出: 123, 456
好的,接下来判断以下代码的输出:
1 const int& a = 123; 2 int& b = const_cast<int&>(a); 3 b = 456; 4 5 std::cout << a << ", " << b << std::endl;
输出: 456, 456
然后还有这段代码的输出:
1 class Item 2 { 3 public: 4 Item() : Item(0) {} 5 Item(int a) : _a(a) {} 6 7 int TestFunc() const 8 { 9 Item& pThis = const_cast- (*this); 10 pThis.Change(); 11 return _a; 12 } 13 14 int TestFunc() 15 { 16 Change(); 17 return _a; 18 } 19 20 private: 21 void Change() { ++_a; } 22 23 public: 24 int _a; 25 }; 26 27 int main() 28 { 29 Item iA(123); 30 const Item iB(123); 31 Item& iC = const_cast
- (iB); 32 ++(iC._a); 33 34 int c = iC._a; 35 int a = iA.TestFunc(); 36 int b = iB.TestFunc(); 37 38 std::cout << a << ", " << b << ", " << c << std::endl; 39 40 return 0; 41 }
输出:124, 125, 124
造成以上的原因:常量折叠 - 高性能架构探索 (ccppcoding.com)
5. 寻找以下代码中的错误(这个属于常识性错误)
1 std::string str1 = "abcdef"; 2 const char* sub1 = str1.substr(1, 2).c_str(); 3 std::cout << sub1 << std::endl;
std::string 的 substr函数返回的是临时变量,用完即销毁,c_str()返回的指针自然也无效。