简体   繁体   中英

Ambiguous call of constructor from overloaded operator function in C++

I'm trying to use an overloaded operator for a class with the following members and functions :

class MyVector {

  private:
    int           *data;
    unsigned int  vector_size;

  public:
    MyVector();
    MyVector(unsigned int n);
    MyVector(unsigned int size, int *in_array=NULL);
    MyVector(const MyVector& copy);
    ~MyVector();
    void print();

    // Assignment operator.
    MyVector& operator=(const MyVector& v);

    friend MyVector operator*(const int &lhs, MyVector &rhs);

    friend MyVector operator*(MyVector &rhs, int &lhs);

    MyVector operator*(MyVector &vector);
};

// Implementing operator overloading.
MyVector operator*(int &lhs, MyVector &rhs);
MyVector operator*(MyVector &lhs, int &rhs);

Inside one of my operator overloading functions, this is what I'm trying to do:

MyVector operator*(const int &lhs, MyVector &rhs) {

    unsigned int size = rhs.vector_size;

    // Create new vector.
    MyVector *v = new MyVector(static_cast<unsigned int>(size));

    for (unsigned int i = 0; i < rhs.vector_size; i++) {
        v -> data[i] = lhs * rhs.data[i];
    }

    return *v;
}

I'm getting the following error :

MyVector_fxns.cpp: In function 'MyVector operator*(const int&, MyVector&)':
MyVector_fxns.cpp:42:60: error: call of overloaded 'MyVector(unsigned int)' is ambiguous
  MyVector *v = new MyVector(static_cast<unsigned int>(size));

Before you mark this as a duplicate, I have checked this link and none of the solutions worked for me.

Out of the three possible constructors, only 1 should be called here. What is causing the error despite me passing the correct type in the constructor argument ?

   MyVector(unsigned int n);
   MyVector(unsigned int size, int *in_array=NULL);

This is ambiguous. Given the above constructors:

MyVector v(10);

This can use either one of these two constructors, with the second constructor's second parameter defaulted. That's what the compiler is complaining about. The compiler doesn't know which constructor to use. It can use either one. It can't decide on its own, or flip or coin, or something. When it comes to compiling C++ code, you can't just flip a coin, and pick a constructor.

The error message states literally this. It's a very clear compilation error:

call of overloaded 'MyVector(unsigned int)' is ambiguous

You have an overloaded constructor. And it's ambiguous.

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