参数化模板 Class 构造函数与另一个模板 class

Parametrized Template Class constructor with another template class

我正在尝试用两个 Complex 变量初始化一个 Calculator。这两个 类 都是模板 类.

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

我主要是:

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

我收到两个仅与 complexCalc 初始化相关的编译时错误,它们是相同的错误:

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(){}
      |         ^~~~~~~

我不知道这意味着什么或如何解决它。

问题是无法区分 Calculator 的零参数构造函数和带默认参数的双参数构造函数。您应该只删除零参数构造函数。