作为对我上一个问题的一个有趣的补充(虽然不是很重要的实际问题) : 为什么 C + + 允许我们在声明变量时把变量名放在括号中?
我发现将括号中的声明与 注入的类名特性相结合可能会导致关于编译器行为的惊人结果。
请看以下节目:
#include <iostream>
struct B
{
};
struct C
{
C (){ std::cout << "C" << '\n'; }
C (B *) { std::cout << "C (B *)" << '\n';}
};
B *y = nullptr;
int main()
{
C::C (y);
}
Compiling with g++ 4.9.2 gives me the following compilation error:
main.cpp:16:10: error: cannot call constructor 'C::C' directly [-fpermissive]
It compiles successfully with MSVC2013/2015 and prints C (B *)
It compiles successfully with clang 3.5 and prints C
So obligatory question is which one is right? :)
(I strongly swayed towards clang version though and msvc way to stop declaring variable after just changing type with technically its typedef seems kind of weird)