4

我有一个 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

}
4

1 回答 1

13

Complex 是一个模板类。所以它在构造时需要一个模板参数。

Complex<int> complexA(10, 5);
        ^^^^ 
于 2013-04-20T06:25:04.857 回答