954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

[Ask] cin >> class object?

hi, i want to ask..

is it can to get an input from the user by only call the class object?

here's the code :

#include

class Time{
private:
int time;
int minute;
int sec;
...
};

void main(){
Time t;
cin >> t;
cout << "The time is : " << t << endl;
}

Is that code wrong or true, but need some additional parts?

please give me a detail and simple explanation because i'm still a newbie. Thank You.

fhast
Newbie Poster
4 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

Use a friend function to overload the >> operator

class Time
{
private:
    int hour, minute, second;
public:
    Time() {hour = mijnute = second = 0;}
    friend istream& operator >> (istream& in, Time& t);
};

// Put this in the *.cpp file, not the *.h file
istream& operator >> (istream& in, Time& t)
{
           cout << "Enter time";
           cin >> t.hour >> t.minute >> t.second;
           return in;
};
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

At this stage(I am assuming), it may be easier( for you) to create a function, like so :

class Timer
{
    int h,m,s;
    public :
     void getTime() { cin >> h >> m >> s; }
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

Use a friend function to overload the >> operator

class Time
{
private:
    int hour, minute, second;
public:
    Time() {hour = mijnute = second = 0;}
    friend istream& operator >> (istream& in, Time& t);
};

// Put this in the *.cpp file, not the *.h file
istream& operator >> (istream& in, Time& t)
{
           cout << "Enter time";
           cin >> t.hour >> t.minute >> t.second;
           return in;
};

Thank You Ancient Dragon, i can use it. now the problem is solved.

@firstperson

yeah, i know it is easier that way, but i see this code (cin >> object class) and i want to know if it is possible to do it.

fhast
Newbie Poster
4 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You