有没有办法在 C++ 中使用匿名类作为返回类型?
我在谷歌上搜索说这可能有效:
struct Test {} * fun()
{
}
但是这段代码编译不通过,报错信息是:
new types may not be defined in a return type
其实这段代码没有任何意义,我只是想弄清楚在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;
}
我用 g++ xx.cpp -std=c++0x 编译这段代码,编译器提示:
expected primary-expression before '[' token.
最佳答案
注意:这些代码片段在最新版本的 g++ 中不再有效。我用 4.5.2 版编译它们,但 4.6.1 和 4.7.0 版不再接受它们。
您可以在 C++11 中将匿名结构声明为 lambda 函数的返回类型。但这并不漂亮。此代码将值 99 分配给 mx
:
int mx = [] () -> struct { int x, y ; } { return { 99, 101 } ; } ().x ;
ideone 输出在这里:http://ideone.com/2rbfM
应程的要求:
lambda 函数是 C++11 中的一个新特性。它基本上是一个匿名函数。这是一个更简单的 lambda 函数示例,它不带任何参数并返回一个 int
:
[] () -> int { return 99 ; }
您可以将其分配给一个变量(您必须使用 auto
来执行此操作):
auto f = [] () -> int { return 99 ; } ;
现在你可以这样调用它:
int mx = f() ;
或者您可以直接调用它(这是我的代码所做的):
int mx = [] () -> int { return 99 ; } () ;
我的代码只使用 struct { int x, y ; }
代替 int
。末尾的 .x
是应用于函数返回值的普通 struct
成员语法。
此功能并不像看起来那么无用。您可以多次调用该函数以访问不同的成员:
auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } ;
cout << f().x << endl ;
cout << f().y << endl ;
您甚至不必调用该函数两次。此代码完全符合 OP 的要求:
auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } () ;
cout << f.x << endl ;
cout << f.y << endl ;
关于c++ - 匿名类可以用作 C++ 中的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8026579/