在Dev C++ 下不能通过编译,why?

zebang 2007-05-01 03:15:32
#include <iostream>
using namespace std;

template <class T>
class A
{
public:
void setx(T a) { x=a; }
void dispa() { cout<<x<<endl; }
T getx() { return x; }
protected:
T x;
};

template <class T1,class T2>
class B:public A<T2>
{
public:
void sety(T1 obj1, T2 obj2) { y=obj1; setx(obj2);}
void dispb() { cout<<y<<" "<<getx()<<endl; }
T1 gety() { return y; }
protected:
T1 y;
};

int main()
{
B <char *,double> obj1;
obj1.setx(12.34);
obj1.dispa();
obj1.sety("The value is" , 56.78);
obj1.dispb();
obj1.dispa();
obj1.setx(90.12);
cout<<obj1.gety()<<endl;
cout<<obj1.getx()<<endl;
obj1.dispb();
B <char *,char *> obj2;
obj2.sety("The result is ","very good.");
obj2.dispb();
B <int, char *> obj3;
obj3.sety(10,"pass");
obj3.dispb();
}
...全文
283 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Tomsdinary 2007-05-02
  • 打赏
  • 举报
回复
20 D:\VC\test\main.cpp there are no arguments to `getx' that depend on a template parameter, so a declaration of `getx' must be available
20 D:\VC\test\main.cpp (if you use `-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)
由以上错误信息我们得知:在模板实例化时getx的名字不见了,或者说编译器无法推倒出getx的返回类型.当我们将对getx调用改成对x的引用时也无法编译通过.这说明编译器甚至连x的类型也不知道.问题究竟在哪呢?我想问题在于编译器实例化模板的顺序上.编译器先实例化类B,然后才是基类A,这样一切就迎刃而解了.当编译器实例化 getx()时,它还没有实例化A,也没有足够的信息告诉编译器getx()与A的实例化有关,当然不知道getx的返回类型,所以getx()的调用是定义的.而其他成员函数实例化是能够被推导的.如: void sety(T1 obj1, T2 obj2)
{
y=obj1;
setx(obj2);
}
由于实例化B时,setx(obj2)并不存在,当实例化A时它才存在.但编译器是怎么知道的呢?秘密在于它知道了obj2的类型,这为setx的实例化提供了依据.而getx()实例化时没有丝毫的信息告诉它.
060 2007-05-01
  • 打赏
  • 举报
回复
错误信息:
22 D:\CPP\TestCode\0501.cpp there are no arguments to `getx' that depend on a template parameter, so a declaration of `getx' must be available

是C++模板参数的问题,在VC2005中可以编译,
将cout<<y<<" "<<getx()<<endl;
改成 cout<<y<<" "<<A<T2>::getx()
在DevC++中也编译通过
nevergone 2007-05-01
  • 打赏
  • 举报
回复
可以编译通过啊.
是不是你看不到结果,有问题

加个在main()函数结尾处加一个cin.get();
believefym 2007-05-01
  • 打赏
  • 举报
回复
int main
你没返回值,加个return 0;试试

65,213

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧