テンプレートを使用して複数のデータ型を比較する isEqualTo 関数があります。最初にすべてを main.cpp ファイルに入れたときはすべて問題ありませんでしたが、Complex クラスをヘッダーと cpp ファイルに分割すると、「クラス テンプレート "Complex" の引数リストがありません」というエラーが表示されます。 . もちろん、クラス複合体のデフォルトのコンストラクターを確認すると、次のようになります。
**main.cpp**
#include <iostream>
#include <string> objects
#include "Complex.h"
using namespace std;
template <class T>
class Complex<T>
bool isEqualTo(T a, T b)
{
if(a==b)
{
cout << a << " is EQUAL to " << b << endl;
return true;
}
else cout << a << " is NOT EQUAL to " << b << endl;
return false;
}
int main()
{
//Comparing Complex class
Complex<int> complexA(10, 5), complexB(10, 54), complexC(10, -5), complexD(-10, -5); //Creating complex class objects
cout << endl << endl << "******Comparing Complex Objects:****** \n";
isEqualTo(complexA, complexA); //true
isEqualTo(complexA, complexB); //false
isEqualTo(complexC, complexA); //false
isEqualTo(complexD, complexD); //true
}
**Complex.h**
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
using namespace std;
template <class T>
class Complex
{
public:
//default constructor for class Complex
Complex(int realPart, int imaginaryPart) : real(realPart), imaginary(imaginaryPart)
//Overloading equality operator
bool operator==(const Complex &right) const //address of our cosnt right operand will have two parts as a complex data type, a real and imaginary
{
return real == right.real && imaginary==right.imaginary; //returns true if real is equal to BOTH of its parts right.real and right.imaginary
}
//overloading insertion operator
friend ostream &operator<<(ostream&, Complex<T>&);
private: //private data members for class Complex
int real; //private data member real
int imaginary; //private data member imaginary
};
#endif
**Complex.cpp**
#include "Complex.h"
#include <iostream>;
using namespace std;
template<class T>
ostream &operator<<(ostream& os, Complex,T.& obj)
{
if(obj.imaginary > 0)//If our imaginary object is greater than 0
os << obj.real << " + " << obj.imaginary << "i";
else if (obj.imaginary == 0) //if our imaginary object is ZERO
os << obj.real; //Then our imaginary does not exist so insert only the real part
else //If no other condition is true then imaginary must be negative so therefor
{
os << obj.real << obj.imaginary << "i"; //insert the real and the imaginary
}
return os; //return the ostream object
}