Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

c++ - Overloaded operator as argument of copy constructor

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...