开发者

How can I write a variable of a user-defined type into a stream

I dont mean a variable in a class but a default value for the class as a whole.

struct Scalar {
    unsigned int value;

    void toThePowerOf(int power);
    // etc.
}

I'd like to be able to do something like

Scaler foo;
foo.value = 2;
foo.toThePowerOf(2);

std::cout << foo << std::endl; // Outputs 4!
开发者_运维技巧

Is that possible in C++?


No, classes do not have a value in the way you're thinking.

What you probably mean to do is to overload the << operator:

ostream& operator<<(ostream& output, const Scalar& val)
{
  output << val.value;
  return output;
}


I meant a default value for the class, so if you called that object by just its name foo it would return foo.value by default.

It is actually possible to define an implicit conversion from Scalar to int:

struct Scalar
{
    unsigned int value;

    operator int() const
    {
        return value;
    }
};

int main()
{
    Scalar foo = {2};
    std::cout << foo << std::endl;
}

But implicit conversions are generally frowned upon in the C++ community, because it can make code quite hard to read. (I guess this is why noone mentioned conversion operators yet.)


No, you cannot but you can overload operator << for your class and ostream to get the desired effect

std::ostream& operator << (std::ostream& out, const Scaler& foo)
{
   return out << foo.value;
}

Your code will now work and produce the desires result


Yes. it is possible. Just initialize all the values in the constructor of the class. Use class instead of struct.


Use a default value in the ctor. Make the ctor explicit if you don't want implicit conversions.

struct Scalar {
  unsigned int value;

  Scalar(int value=0) : value (value) {}

  void toThePowerOf(int power) {
    // naive implementation just for show
    int new_value = 1;
    assert(power >= 0);  // or other error checking
    for (; power > 0; --power) {
      new_value *= value;
    }
    value = new_value;
  }

  friend std::ostream& operator<<(std::ostream &out, Scalar const &x) {
    out << x.value;
    return out;
  }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜