简体   繁体   中英

How to return a struct from a class in C++?

I have a problem in returning a struct from a method declared in a class. The struct i is composed by 3 integers: day , month and year . I set these three values using a method in the class.

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

Then I have a method to return the full struct

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

But I get lots of errors in compiling. What should I do?

I've also read Is it safe to return a struct in C or C++? but I haven't solved my issue.

The program is composed from main.cpp , Difference.h and Date.h

Errors in Date.h :

[Error] 'dmy' does not name a type

Main

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;
}

Date.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;
}

NOTE: The struct was called ' i '

Example

#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;
}

Build

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

instead of

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

write

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

since "dmy" is not in the global namespace.

Try this:

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 - class
  • C1::S1 - struct inside class C1
  • C1::f1 - function returning C1::S1

I doubt that your source code is compiled in the C style other that C++ style. You could try to change the file extension to ".cpp" instead of ".c" and then gcc will do it's job in C++ style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM