"Markus Dehmann" <markus.cl@gmx.de> wrote in message
news:c1e48b51.0405202058.36d10b76@posting.google.c om...[color=blue]
> 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(value){}
> };
>
> class StringValue : public Value{ // constructor etc omitted
> private:
> std::string _value;
> public:
> StringValue(std::string value):_value(value){}
> };
>
> But how do I realize the << operator? I could do sth like this, then:
>
> int main(){
> vector <Value> val;
> values.push_back(IntValue(3));
> values.push_back(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?[/color]
Buy a book on C++, look up the chapter on polymorphism and virtual
functions. Also don't try to program C++ by analogy with Java, you'll end up
programming only the common ground between Java and C++ which won't get you
very far. Here's some untested sample code
class Value
{
public:
virtual ~Value() {}
virtual void print(ostream& os) const = 0;
};
class IntValue : public Value{
private:
int _value;
public:
IntValue(int value):_value(value){}
void print(ostream& os) const
{
os << _value;
}
};
class StringValue : public Value{ // constructor etc omitted
private:
std::string _value;
public:
StringValue(std::string value):_value(value){}
void print(ostream& os) const
{
os << _value;
}
};
std::ostream & operator<<(std::ostream & out, const Value& x)
{
x.print(out);
return out;
}
And of course like Victor says, you must store pointers or smart pointers in
your vector. Try googling for smart pointer, or check out shared_ptr at
www.boost.org
john