简体   繁体   中英

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;
}

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;
  }
};

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM