Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to use copy constructor with the result of my overloaded operator*. I found the way to do this: by returning reference from the operator. What I would like to know:

  1. Is this okay?

Here is the example:

class Foo{
    public:
        double x,y,z;
        Foo() : x(0), y(0), z(0) {};
        Foo(double xi, double yi, double zi) : x(xi), y(yi), z(zi) {};
        Foo(const Foo &bar) : x(bar.x), y(bar.y), z(bar.z) {};
};

Foo& operator * (const double &b, Foo &a){ // Yep, I want to modify a
    a.x *= b;
    a.y *= b;
    a.z *= b;
    return a;
}

int main(){
    Foo temp;
    Foo bar = 4*temp; // Here is what I want to do!

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

With operator *, we expect:

  • the two inputs to remain unmodified,
  • a new object to be returned (by value).

which gives us the following signature:

Foo operator * (double a, Foo const & b);

If you want to modifiy temp = 4*temp, use operator *= as temp *= 4; instead, which modifies temp and returns its reference:

Foo & operator *= (Foo & a, double b) {
    a.x *= b;
    a.y *= b;
    a.z *= b;
    return a;
}

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...