C++ 每日一题
所有题目均出自C++ Quiz
2022-02-15
根据C++17标准,下列程序的输出是什么?
#include <iostream>
struct X {
X() { std::cout << "1"; }
X(const X &) { std::cout << "3"; }
~X() { std::cout << "2"; }
void f() { std::cout << "4"; }
} object;
int main() {
X(object);
object.f();
}
答案 : 11422
解释
首先,全局X object(global X object)被创建,输出1
然后进入main
函数,对于X(object)
可以有两种解释方式:
- 创建了一个object的一个临时匿名拷贝
- 创建一个类型为X名称为object的新的变量。如果把括号去掉的话,变成
X object
,就更容易发现这种解释.
在C++标准了有这样的解释:
An expression-statement with a function-style explicit type conversion (§8.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.
一个具有函数样式显式类型转换的表达式语句,其最左侧子表达式的表达式语句与第一个声明符以 ( 开头的声明无法区分。在这些情况下,该语句是一个声明。
因此,在该题中,X(object)
实际上声明了一个新的局部变量,隐藏掉了全局object,此时调用了一次构造函数,输出1.
之后,调用f()
,输出4。
接下来,退出main
,局部object被析构,输出2。最后,全局object函数被析构,输出2。
2022-02-16
根据C++17标准,下列程序的输出是什么?
#include <iostream>
using namespace std;
int foo() {
cout << 1;
return 1;
}
void bar(int i = foo()) {}
int main() {
bar();
bar();
}
答案 : 11
解释
foo()
函数被调用1次还是两次?
在C++标准了有这样的解释:
“A default argument is evaluated each time the function is called with no argument for the corresponding parameter.”
每次调用没有对应形参实参的函数时,都会计算默认实参。
因此foo()
被调用了两次