I am trying to initialize a Calculator
with two Complex
variables. Both these classes are template classes.
calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H
template <class U>
class Calculator{
private:
U left_val;
U right_val;
public:
Calculator(){}
Calculator(U m_left_val, U m_right_val){
left_val = m_left_val;
right_val = m_right_val;
}
U add();
U subtract();
};
#endif
complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
template <class T>
class Complex{
private:
T m_real;
T m_imaginary;
public:
Complex(){}
Complex(T real = 0 , T imaginary = 0){
m_real = real;
m_imaginary = imaginary;
}
Complex operator (const Complex& complex);
Complex operator - (const Complex& complex);
};
#endif
In my main:
Calculator<double> floatCalc(30.3, 20.7);
Calculator<int> intCalc(100, 30);
Complex<double> a(2.0, 4.0);
Complex<double> b(1.0, 2.0);
Calculator<Complex<double>> complexCalc(a, b); //This is the line in question
I am getting two compile time errors that only relate to the initialization of complexCalc
and they are the same error:
In file included from main.cpp:3:
calculator.h: In instantiation of 'Calculator<U>::Calculator() [with U = Complex<double>]':
main.cpp:11:33: required from here
calculator.h:10:21: error: call of overloaded 'Complex()' is ambiguous
10 | Calculator(){}
| ^
In file included from main.cpp:2:
complex.h:11:9: note: candidate: 'Complex<T>::Complex(T, T) [with T = double]'
11 | Complex(T real = 0 , T imaginary = 0){
| ^~~~~~~
complex.h:10:9: note: candidate: 'Complex<T>::Complex() [with T = double]'
10 | Complex(){}
| ^~~~~~~
In file included from main.cpp:3:
calculator.h:10:21: error: call of overloaded 'Complex()' is ambiguous
10 | Calculator(){}
| ^
In file included from main.cpp:2:
complex.h:11:9: note: candidate: 'Complex<T>::Complex(T, T) [with T = double]'
11 | Complex(T real = 0 , T imaginary = 0){
| ^~~~~~~
complex.h:10:9: note: candidate: 'Complex<T>::Complex() [with T = double]'
10 | Complex(){}
| ^~~~~~~
I don't know what this means or how to fix it.
CodePudding user response:
The issue is that there's no way to differentiate between the zero parameter constructor of Calculator
, and the two parameter constructor with default arguments. You should just remove your zero parameter constructor.