我的老师刚刚将此作为即将到来的 C++ 期中考试的几个程序示例之一。代码是:
//What does this program print?
#include <iostream>
using namespace std;
#define foo1( a ) a * a
int j = 6;
inline int
foo2( int a )
{
return a * a;
}
void
goo1( int& x )
{
x = 3;
}
void
goo2( int x )
{
x = 3;
}
int main()
{
int i, j = 12;
cout << "foo1 = " << foo1( 3 + 2 ) << "\n";
cout << "foo2 = " << foo2( 3 + 2 ) << "\n";
i = 5;
goo1( i );
cout << "goo1 = " << i << "\n";
i = 5;
goo2( i );
cout << "goo2 = " << i << "\n";
cout << " j = " << j << "\n";
cout << "::j = " << ::j << "\n";
}
谁能解释一下 foo1 = 11 是如何产生的。我已经用不同的数字进行了一个小时的试验,但我无法确切地理解它是如何计算出来的。
最佳答案
foo1 是一个宏。宏执行严格的查找和替换,因此 foo1(3+2) 被替换为 3+2*3+2。 按照运算顺序,3+2*3+2 = 3+6+2 = 11。
关于c++ - 解释期中 C++ 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16456791/