Complex.h #pragma once #include<iostream> using namespace std;//这句还必须加,要不然致错,不懂为啥呢 template <typename T> class Complex { public: Complex( T a); ~Complex(); Complex operator + (Complex & c1); public: friend ostream & operator << <T> (ostream &out, Complex & c2); private: T a; };
Complex.cpp #include "Complex.h" template <typename T> Complex<T>::Complex(T a ) { this->a = a; } template <typename T> Complex<T>::~Complex() { } template <typename T> Complex<T> Complex<T> ::operator + (Complex<T> & c1) { this->a = this->a + c1.a; return *this; } template <typename T> ostream & operator << (ostream &out, Complex <T> & c2) { out << c2.a; return out; }
test.cpp #include<iostream> #include"Complex.cpp"//这里至关重要!!! using namespace std; int main() { Complex <int> a(5); cout << a; system("pause"); return 0; }
要包含.cpp这点异于常类 易错误
时间: 2024-12-15 06:55:33