Reputation: 1260
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'
Upvotes: 1
Views: 4085
Reputation: 36082
instead of
dmy Date::getS(){
return c;
}
write
Date::dmy Date::getS(){
return c;
}
since "dmy" is not in the global namespace.
Upvotes: 1
Reputation: 41
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.
Upvotes: 0
Reputation: 8481
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
Upvotes: 2
Reputation: 51835
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();
}
Upvotes: 0