This question has already been answered:
- operator () overload (int, int) and inheritance 2 responses
Hello! Please explain why this happens. I do not lay out the code entirely, but only its individual pieces, which, it seems to me, will help to understand the essence of what is happening.
I have a class called DynamicArray , which defines the overloading of the operator * that performs the scalar multiplication of two vectors.
class DynamicArray { public: // конструкторы DynamicArray(int n); // конструктор по количеству элементов DynamicArray(int *newArr, int n); // конструктор по массиву и количеству элементов DynamicArray(const DynamicArray &obj); // конструктор копирования ~DynamicArray(); // деструктор double operator*(DynamicArray obj2); // перегрузка оператора умножения (скалярное произведение) // еще небольшая кучка кода }; Also, I have a class MyVector , which is inherited from the class DynamicArray .
class MyVector : public DynamicArray { public: // конструкторы MyVector(int n) : DynamicArray(n) {} ; // конструктор по количеству элементов MyVector(int *newArr, int n) : DynamicArray(newArr, n) {}; // конструктор по массиву и количеству элементов // еще небольшая кучка кода }; If I run the program in this form, then everything works fine and objects like MyVector multiply perfectly with each other as follows:
MyVector vec1(3); MyVector vec2(3); cout << vec1*vec2; But for MyVector, I need to add another multiplication operation by a number (which I also want to do with the operator * overload).
But when I declare an overload of multiplication by a number inside the class MyVector , scalar multiplication stops working.
class MyVector : public DynamicArray { public: // конструкторы MyVector(int n) : DynamicArray(n) {} ; // конструктор по количеству элементов MyVector(int *newArr, int n) : DynamicArray(newArr, n) {}; // конструктор по массиву и количеству элементов MyVector operator*(double n); // c этой строчкой всё перестает работать // еще небольшая кучка кода }; But if I redefine the scalar multiplication inside the inherited MyVector and add the following line, then everything starts working again:
MyVector operator*(MyVector obj2); // перегрузка опреатора умножения и всё снова начинает работать The compiler writes the following:
main.cpp: In function 'int main()': main.cpp:31:14: error: no match for 'operator*' (operand types are 'MyVector' and 'MyVector') cout << vec1*vec2; ~~~~^~~~~ In file included from main.cpp:7:0: MyVector.h:38:11: note: candidate: MyVector MyVector::operator*(double) MyVector operator*(double n); // перегрузка опреатора умножения (на число) ^~~~~~~~ MyVector.h:38:11: note: no known conversion for argument 1 from 'MyVector' to 'double' Why does he stop seeing scalar multiplication inside the base class DynamicArray when adding multiplication by a number?