【问题标题】:How to return struct declared in the same class with function?如何返回与函数在同一类中声明的结构?
【发布时间】:2013-12-30 16:33:30
【问题描述】:

我的头文件中有一个类声明,如下所示。一个函数使用一个结构作为输入,另一个作为返回参数。关键是当我以这种方式使用编译器时会出错。

原因是什么?任何想法都值得赞赏。

#include <string>

using namespace std;

namespace My_Functions
{
    class My_Functions
    {

    public:
        struct {

            char input_a;
            int input_b;
            double input_c;
            double input_d;
            double input_e;
            double input_f;
            double input_g;

        } Input_Parameters;

        struct {

            char output_a;
            int output_b;
            double output_c;
            double output_d;
            int output_e;

        } Output_Parameters;

    public:
        Output_Parameters FindExit(Input_Parameters input);


    };

}

在cpp文件中

My_Functions::Output_Parameters My_Functions::FindExit(My_Functions::Input_Parameters input)
{

}

【问题讨论】:

  • struct {} Xstruct X {} 之间存在差异。
  • 您声明了变量匿名结构,名称分别为 Output_Parameters 和 Input_Parameters。

标签: c++ function class visual-c++ struct


【解决方案1】:

有三种方法可以解决您的问题。

A. struct struct_name {}; -> 这个声明结构叫做 'structure_name'

B. typedef struct {}struct_name; -> 如果您不想在名称前使用“struct”关键字,则在结构前使用 typedef 会很有用。

C.在函数原型中使用struct关键字。

struct Output_Parameters FindExit(struct Input_Parameters input);

例如 A:

    struct Input_Parameters {

        char input_a;
        int input_b;
        double input_c;
        double input_d;
        double input_e;
        double input_f;
        double input_g;

    } ;

    struct Output_Parameters{

        char output_a;
        int output_b;
        double output_c;
        double output_d;
        int output_e;

    }; 

【讨论】:

  • @LightnessRacesinOrbit LOL.. 不不。我认为这些定义是不言自明的。我现在将添加一些解释。
  • 我认为如果他们对 OP 是不言自明的,那么他就不会发布这个问题 ;)
  • "如果您不想在名称之前使用 'struct' 关键字,则在结构之前使用 typedef 将很有用" 您已经不必在 C++ 中这样做,并且在相关说明中您C 答案实际上是错误的。否则更好:)
猜你喜欢
  • 1970-01-01
  • 2021-08-25
  • 2021-08-08
  • 2012-09-26
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
相关资源
最近更新 更多