我只是想知道为什么这小段代码在Visual Studio中正确编译(并且没有警告).也许结果与GCC和Clang相同,但不幸的是我现在无法测试它们.
struct T {
int t;
T() : t(0) {}
};
int main() {
T(i_do_not_exist);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 考虑:
struct Foo {
enum { bar };
explicit Foo(int){}
};
struct Baz { explicit Baz(Foo){} };
Baz b(Foo(Foo::bar)); // #1
Run Code Online (Sandbox Code Playgroud)
第1行是最令人烦恼的解析,即使它Foo::bar是一个限定ID并且不可能是一个有效的参数名称?Clang和GCC不同意 ; 哪个编译器是正确的?
如果我编写以下程序,它可以正常工作:
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
int main () { Foo("hello, world"); }
Run Code Online (Sandbox Code Playgroud)
但是,如果我编写一个稍微不同的程序,我会收到编译错误:
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
std::string x("hello, world");
int main () { Foo(x); }
Run Code Online (Sandbox Code Playgroud)
错误是:
prog.cc: In function 'int main()':prog.cc:10:20: error: no matching function for call to 'Foo::Foo()'
为什么第二个程序出错而不是第一个出错?
我试图创建通用的流类持有者,但似乎我无法传递std::cout给它,代码:
#include <iostream>
struct x
{
std::ostream &o;
x(std::ostream &o):o(o){}
};
int main()
{
x(std::cout);
x.o<<"Hi\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译时失败:
c++ str.cc -o str -std=c++11
str.cc: In function ‘int main()’:
str.cc:11:14: error: invalid use of qualified-name ‘std::cout’
str.cc:12:4: error: expected unqualified-id before ‘.’ token
Run Code Online (Sandbox Code Playgroud)
为什么?