I have a two different value types with which I want to do similar
things: store them in the same vector, stack, etc. Also, I want an <<
operator for each of them.
class Value{}; // this would be "public interface Value{}" in Java!
class IntValue : public Value{
private:
int _value;
public:
IntValue(int value):_value(v alue){}
};
class StringValue : public Value{ // constructor etc omitted
private:
std::string _value;
public:
StringValue(std ::string value):_value(v alue){}
};
But how do I realize the << operator? I could do sth like this, then:
int main(){
vector <Value> val;
values.push_bac k(IntValue(3));
values.push_bac k(StringValue(" test"));
for ( vector<Value>:: iterator it = val.begin(); it != val.end();
++it ){
cout << *it;
}
}
I tried defining it empty in the base class and with a non-empty
implementation in IntValue and StringValue, but it gives me compile
errors (can't find the operator)
class Value{
std::ostream & operator<<(std: :ostream & out){}
};
So, how can I do it?
Thanks
Marks
things: store them in the same vector, stack, etc. Also, I want an <<
operator for each of them.
class Value{}; // this would be "public interface Value{}" in Java!
class IntValue : public Value{
private:
int _value;
public:
IntValue(int value):_value(v alue){}
};
class StringValue : public Value{ // constructor etc omitted
private:
std::string _value;
public:
StringValue(std ::string value):_value(v alue){}
};
But how do I realize the << operator? I could do sth like this, then:
int main(){
vector <Value> val;
values.push_bac k(IntValue(3));
values.push_bac k(StringValue(" test"));
for ( vector<Value>:: iterator it = val.begin(); it != val.end();
++it ){
cout << *it;
}
}
I tried defining it empty in the base class and with a non-empty
implementation in IntValue and StringValue, but it gives me compile
errors (can't find the operator)
class Value{
std::ostream & operator<<(std: :ostream & out){}
};
So, how can I do it?
Thanks
Marks
Comment