Hello, the program I am writing takes an intiial menu selection, between class object Double and Integer, and then adds/subs/mul/divs based upon what the user has selected. I believe I have most of the code, except the ability to take the objects from the user. Obviously, cin won't work, and I am unsure about using istream/ostream. Here is a sample of the code. Is there a simple way to do this?
1 2 3 4 5 6 7 8 9 10 11
void doubleAdd()
{
Double d, d3, d4;
cout << "Enter your first double." << endl;
//Input from user (d)
cout << "Enter your second double." << endl;
//Input from user (d4)
d3 = d.add(d4);
cout << d3.toDouble() << endl;
m.waitKey();
}
Tell the compiler what it means to extract a Double from an input stream, by defining the function
std::istream& operator>> (std::istream& is, Double& d);
This will allow std::cin (which is a sort of std::istream) to work with objects of type Double. This is a simple example of generic programming, one of the primary strengths of C++.
If you post your class, we'd be able to help you write it.
Since the data members of Double are private and can't be set outside the constructor, you have to do this indirectly. First, create Double::read() to read from a stream:
1 2 3 4 5 6 7 8
class Double
{
...
public:
std::istream & read(std::istream &is) {
return is >> data >> data2;
};
...
Then outside class Double, you can define the >> operator and have it call read();
1 2 3 4
std::istream &operator>> (std::istream& is, Double& d)
{
return d.read(is);
}
#include <iostream>
usingnamespace std;
class MyClass
{
public:
MyClass(double d) : d_(d)
{
}
constdouble& Data() const
{
return d_;
}
// In order to change private values directly
friend istream& operator>>(istream& is, MyClass& m);
private:
double d_;
};
// Outputting custom class to ostream
ostream& operator<<(ostream& os, const MyClass& m)
{
os << m.Data();
return os;
}
// Inputting custom class to istream
istream& operator>>(istream& is, MyClass& m)
{
is >> m.d_;
return is;
}
int main()
{
MyClass m(45.67);
cout << "MyClass is set to " << m << endl;
cout << "Enter new value for data: ";
cin >> m;
cout << "MyClass is now set to " << m << endl;
}
MyClass is set to 45.67
Enter new value for data: 32.3
MyClass is now set to 32.3
What about if I needed to take in two values? Like in the case of my program, I'm taking two numbers and sending them to my programs in order to add/sub/etc based upon what the user chose in a menu?
The istream stuff for a custom class is usually for imitating the constructor for that class. Like if I had a Time(int hours, int minutes) constructor, I could overload and read in a space-separated Time like:
1 2
is >> t.hours_ >> t.minutes_;
return is;
You could make a complex istream setup, but that wouldn't be intuitive to the user of that class.