#include <iostream>
using namespace std;
template<class type>
class Complex
{
type real,imag;
public:
Complex(){real=0,imag=0;}
Complex(type r,type i){real=r;imag=i;}
Complex & operator+(const Complex &n);
};
Complex<class type>
Complex<type> & Complex<type>::operator+(const Complex<type> &n)
// invalid use of template-name 'Complex' without an argument list|
{
return Complex<type>(real+n.real,imag+n.imag);
}
int main( )
{
return 0;
}
一个简单的模板类 为什么我标记的那行会报错?该怎么改啊
你好,看了你的代码!
你这是定义了个模板类Complex; 其内部有一个成员函数为:运算符重载函数。其函数体定义在类的外部,从函数来看应该是(实部+虚部)。
错在第12行,成员函数(模板函数)的外部定义。改为
template<class type> // 就是这里错误。Complex<class type>改为 template<class type>
Complex<type>& Complex<type>::operator+(const Complex<type> &n)
{
return Complex<type>(real+n.real,imag+n.imag);
}
-----------------
给分我吧~~!
可以参考《C++ Primer》中关于类模板成员函数的定义:
16.4.1. Class-Template Member Functions
16.4.1. 类模板成员函数
The definition of a member function of a class template has the following form:
类模板成员函数的定义具有如下形式:
It must start with the keyword template followed by the template parameter list for the class.
必须以关键字 template 开关,后接类的模板形参表。
It must indicate the class of which it is a member.
必须指出它是哪个类的成员。
The class name must include its template parameters.
类名必须包含其模板形参。
From these rules, we can see that a member function of class Queue defined outside the class will start as
从这些规则可以看到,在类外定义的 Queue 类的成员函数的开关应该是:
template <class T> ret-type Queue<T>::member-name
所以, 你的代码需要做如下更改:
template <class type>//Complex<class type>