I have made a Date class. It takes input and display output correctly. But how can I use this class in structures. Because the data is actually saved in variables y,m,d
Since how is obvious, just put the name in the struct, I'm guessing you are confused about how to call the constructor to initialize the thing. Since a class really is a struct, a struct initializer will call the constructor for the embedded class. Here's an example.
#include <iostream>
using namespace std;
class Date_Time
{
public:
int Date;
int Time;
Date_Time(const int date, const int time)
{
Date = date;
Time = time;
};
};
int main() {
struct state {
Date_Time dt;
} st = {{5, 6}};
cout << "Date: " << st.dt.Date << endl;
cout << "Time: " << st.dt.Time << endl;
}
I compiled with:
g++ -std=c++0x foo.cpp
An alternative is to put a pointer to the class in the struct and initialize it with new
.