我正在嘗試Calculator用兩個Complex變數初始化 a 。這兩個類都是模板類。
計算器.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
復雜的.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(){}
| ^~~~~~~
我不知道這意味著什么或如何解決它。
uj5u.com熱心網友回復:
問題是沒有辦法區分 的零引數建構式Calculator和具有默認引數的兩個引數建構式。您應該只洗掉零引數建構式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467032.html
