c++ - 匿名类可以用作 C++ 中的返回类型吗?

标签 c++ anonymous-types anonymous-class

有没有办法在 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/

相关文章:

asp.net-mvc-2 - 使用 'class'(或其他保留关键字)作为匿名类型的属性

c# - 为什么 RazorEngine 会动态编译带有匿名类型模型的模板?

C++ 运算符 << 重载

c++ - 可以在循环之外打破循环吗?

c# - 在匿名类型的属性名称中使用异常(exception)字符(减号)

java - 是否可以向匿名类添加属性而不是仅覆盖其方法?

java - 如何在方法内部测试匿名类对象

java - 抽象类和匿名类

C++ 模板协变

c++ - 更改 inf 的 Visual C++ 输出