【问题标题】:How to return a struct from a class in C++?如何从 C++ 中的类返回结构?
【发布时间】:2014-01-23 11:50:32
【问题描述】:

我在从类中声明的方法返回结构时遇到问题。 struct i 由 3 个整数组成:daymonthyear。 我使用类中的方法设置这三个值。

struct dmy{
   int day, month, year;
};
dmy c;

然后我有一个方法可以返回完整的结构

dmy Date::getS(){
  return c;
}

但我在编译时遇到很多错误。我该怎么办?

我也阅读了Is it safe to return a struct in C or C++?,但我的问题还没有解决。

程序由main.cppDifference.hDate.h组成

Date.h 中的错误:

[Error] 'dmy' does not name a type

主要

using namespace std;

#include <iostream>
#include "Date.h"

int main(int argc, char** argv) {

    Date date1;
    Date date2;

    cout<<"Insert first date\n";
    date1.setAll();

    return 0;
}

日期.h

class Date{
public:
    Date(){
    }
    ~Date(){
    }
    void setAll();
    struct dmy{
        int day, month, year;
    };
    dmy c;
    dmy getS();
private:
    void setDay();
    void setMonth();
    void setYear();
};

void Date::setAll(){
    setDay();
    setMonth();
    setYear();
}

void Date::setDay(){
    do{
        cout<<"Type day: ";
        cin>>c.day;
    }while(0<c.day<31);
}

void Date::setMonth(){
    //didn't right the checking again
    cout<<"Type month: ";
    cin>>c.month;
}

void Date::setYear(){
    cout<<"Type year: ";
    cin>>c.year;
}

dmy Date::getS(){
    return c;
}

注意:该结构被称为'i'

【问题讨论】:

  • 显示你的错误。对于有经验的人来说,错误可以准确地说明问题所在以及如何解决。
  • 向我们展示您遇到的错误。
  • 好吧,不幸的是,我正在用平板电脑写字,所以这并不容易。在学校,我们没有互联网接入。
  • 你是否在头文件中声明struct i?你包含那个头文件吗?
  • 另外,你可能不应该将你的结构命名为 ii 通常用作变量名。

标签: c++ struct


【解决方案1】:

示例

#include <cstdio>
#include <cstdlib>

struct DateInfo {
   int day;
   int month;
   int year;
};

class Date {
 public:
   Date(const int day, const int month, const int year) : m_info( { day, month, year } )
   {
      //n/a
   }

   DateInfo get_info( void ) const
   {
     return m_info;
   }

 private:
   DateInfo m_info;
};

int main( int, char** )
{
   Date date( 29, 02, 1984 );

   DateInfo info = date.get_info( );

   printf( "%i\n", info.year );

   return EXIT_SUCCESS;
}

构建

g++ -std=c++11 -o date date.cpp

【讨论】:

    【解决方案2】:

    而不是

    dmy Date::getS(){
        return c;
    }
    

    Date::dmy Date::getS(){
        return c;
    }
    

    因为“dmy”不在全局命名空间中。

    【讨论】:

    • 如果 dmy 是一个嵌套类,那将是正确的。但不是
    【解决方案3】:

    试试这个:

    class C1
     {
    public:
     struct S1
      {
      int a,b,c;
      };
    
     S1 f1() { S1 s; return s; }
     };
    
    void main()
     {
     C1 c;
     C1::S1 s;
    
     s=c.f1();
     }
    
    • C1 - 类
    • C1::S1 - 类 C1 中的结构
    • C1::f1 - 函数返回 C1::S1

    【讨论】:

    • 在类中嵌入结构定义可能会导致编译时依赖性问题。如果您更改 S1 结构,则包括 C1 标头在内的所有结构都需要重新编译。好处可以来自提取结构并在需要时向前声明它。见编译防火墙c2.com/cgi/wiki?PimplIdiom
    【解决方案4】:

    我怀疑您的源代码是以 C++ 风格以外的 C 风格编译的。您可以尝试将文件扩展名更改为“.cpp”而不是“.c”,然后 gcc 将以 C++ 风格完成它的工作。

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2013-03-02
      • 2020-05-31
      • 1970-01-01
      相关资源
      最近更新 更多