我已经删除了所有不需要的片段。我正在尝试将指针传递给重载运算符并也使用模板。但这仍然不起作用。
#include<iostream.h>
#include<conio.h>
class Test{
private:
int a;
public:
Test (){}
Test(int k){
a=k;
}
Test* operator +(Test *p){
Test *temp=new Test(this->a+p->geta());
return temp;
}
int geta(){
return a;
}
};
template<class T>
T* sum(T* a,T* b){
return a+b;
}
int main(){
Test *t1,*t2;
t1=new Test(5);
t2=new Test(7);
Test *z=sum(t1,t2);
cout<<z->geta();
getch();
}
最佳答案
首先,t1
是一个指针,您错误地调用了 add
方法 - 应该是 t1->add(t2)
。其次,sum()
方法采用的参数不是指针,即模板参数被推导为 Test
而不是 Test*
,因此您需要将签名更改为:
template <typename T>
T* sum(T* a, T* b)
{
return a->add(b); // or some variant...
}
关于c++ - 无法将指针传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5179966/