以下代码编译并运行时,我感到很惊讶(vc2012&gcc4.7.2)
class Foo {
struct Bar { int i; };
public:
Bar Baz() { return Bar(); }
};
int main() {
Foo f;
// Foo::Bar b = f.Baz(); // error
auto b = f.Baz(); // ok
std::cout << b.i;
}
Run Code Online (Sandbox Code Playgroud)
这段代码编译得好吗?为什么这是正确的?为什么我可以auto在私有类型上使用,而我不能使用它的名字(如预期的那样)?
我在这里阅读模板别名:http://en.cppreference.com/w/cpp/language/type_alias
我想知道,即使它写在我链接的页面的第一行,typedef和类型别名(using mytype = T;)之间的区别是什么
它们不可互换吗?
有没有办法在C++中使用匿名类作为返回类型?
我用谷歌搜索这可行:
struct Test {} * fun()
{
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码没有编译,错误信息是:
可能无法在返回类型中定义新类型
实际上代码没有任何意义,我只是想弄清楚一个匿名类是否可以在C++中用作返回类型.
这是我的代码:
#include <typeinfo>
#include <iterator>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main(int argc, char **argv)
{
int mx = [] () -> struct { int x, y ; } { return { 99, 101 } ; } ().x ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我用g ++ xx.cpp -std = c ++ 0x编译这段代码,编译器得到:
expected primary-expression before '[' token.
Run Code Online (Sandbox Code Playgroud)