匿名类可以用作C

匿名类可以用作C

本文介绍了匿名类可以用作C ++中的返回类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用C ++中的匿名类作为返回类型?

Is there any way to use anonymous classes in C++ as return types?

我在Google上搜索这可能有效:

I googled that this may work:

struct Test {} * fun()
{
}

但是这段代码无法编译,错误消息是:

But this piece of code doesn't compile, the error message is:

实际上,代码没有任何意义,我只想弄清楚是否可以将匿名类用作C ++中的返回类型.

Actually the code doesn't make any sense, I just want to figure out whether an anonymous class can be used as return type in 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编译此代码,编译器会编译:

I compile this code with g++ xx.cpp -std=c++0x, the compiler compains:

expected primary-expression before '[' token.

推荐答案

注意:这些代码段在最新版本的g ++中不再起作用.我使用4.5.2版进行了编译,但是4.6.1和4.7.0版不再接受它们.

Notice: These code snippets no longer work in the latest versions of g++. I compiled them with version 4.5.2, but versions 4.6.1 and 4.7.0 no longer accept them.

可以声明一个匿名结构作为C ++ 11中lambda函数的返回类型.但这并不漂亮.此代码将值99分配给mx:

You can declare an anonymous struct as the return type of a lambda function in C++11. But it's not pretty. This code assigns the value 99 to mx:

int mx = [] () -> struct { int x, y ; } { return { 99, 101 } ; } ().x ;

此处是ideone的输出: http://ideone.com/2rbfM

The ideone output is here: http://ideone.com/2rbfM

应程的要求:

lambda函数是C ++ 11中的新功能.它基本上是一个匿名函数.这是lambda函数的一个简单示例,该函数不带任何参数并返回int:

The lambda function is a new feature in C++11. It's basically an anonymous function. Here is a simpler example of a lambda function, that takes no arguments and returns an int:

[] () -> int { return 99 ; }

您可以将其分配给变量(必须使用auto来做到这一点):

You can assign this to a variable (you have to use auto to do this):

auto f = [] () -> int { return 99 ; } ;

现在您可以这样称呼它:

Now you can call it like this:

int mx = f() ;

或者您可以直接调用它(这是我的代码所做的):

Or you can call it directly (which is what my code does):

int mx = [] () -> int { return 99 ; } () ;

我的代码仅使用struct { int x, y ; }代替int.最后的.x是应用于函数返回值的常规struct成员语法.

My code just uses struct { int x, y ; } in place of int. The .x at the end is the normal struct member syntax applied to the function's return value.

此功能并不是像看起来的那样有用.您可以多次调用该函数以访问不同的成员:

This feature is not as useless as it might appear. You can call the function more than once, to access different members:

auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } ;
cout << f().x << endl ;
cout << f().y << endl ;

您甚至不必两次调用该函数.这段代码完全符合OP的要求:

You don't even have to call the function twice. This code does exactly what the OP asked for:

auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } () ;
cout << f.x << endl ;
cout << f.y << endl ;

这篇关于匿名类可以用作C ++中的返回类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:22