向C++高手求救

来源:百度知道 编辑:UC知道 时间:2024/04/29 10:11:29
#include<iostream.h>
template <class type1> class ab
{
type1 d,c;
public: ab( type1 d,type1 c){this->d=d;this->c=c;}
void swap(type1 d,type1 c);
void print();
};
template <class type1> void ab<type1>::
swap(type1 d,type1 c)
{type1 temp;
temp=d;
d=c;
c=temp;}
template <class type1> void ab<type1>::print(){cout<<d<<c<<endl;}
int main()
{
ab a(5,2);
ab *P;
p=&a;
p->swap();
p->print();
return 1;
}
为什么说a 未被申明

你要这样用才行:
ab<int> a(5,2);

ab是个模板类,你没有告诉编译器ab的类型,所以未必声明!

正确写法为:

ab<int> a(5,2);
ab<double> *P;

模板不是你这样用的,申明的时候你要指定模板类型。比如ab<int> a(5,2);就行了。

#include<iostream.h>
template <class type1> class ab
{
type1 d,c;
public: ab( type1 d,type1 c){this->d=d;this->c=c;}
void swap(); //不需要参数
void print();
};
template <class type1> void ab<type1>::
swap()
{type1 temp;
temp=d;
d=c;
c=temp;}
template <class type1> void ab<type1>::print(){cout<<d<<c<<endl;}
int main()
{
ab<int> a(5,2); //声明错误
ab<int> *p;//注意大小写
p=&a;
p->swap();
p->print();
return 1;
}