我试图将模板应用到原始课程中。但我得到的错误是无法隐蔽'移动'到' int'作为回报。请帮帮....
这是模板。错误在第40行
#ifndef MOVE0_H_
#define MOVE0_H_
template <typename Type>
class Move
{
private:
double x;
double y;
public:
Move(double a = 0, double b = 0); // sets x, y to a, b
void showmove() const; // shows current x, y values
int add(const Move & m) const;
// this function adds x of m to x of invoking object to get new x,
// adds y of m to y of invoking object to get new y, creates a new
// move object initialized to new x, y values and returns it
void reset(double a = 0, double b = 0); // resets x,y to a, b
};
template<typename Type>
Move<Type>::Move(double a, double b)
{
x = a;
y = b;
}
template<typename Type>
void Move<Type>::showmove() const
{
std::cout << "x = " << x << ", y = " << y;
}
template<typename Type>
int Move<Type>::add(const Move &m) const
{
Move temp;
temp.x = x + m.x;
temp.y = y + m.y;
return temp;
}
template<typename Type>
void Move<Type>::reset(double a, double b)
{
x = 0;
y = 0;
}
#endif
以下是主程序,该程序位于第23行
#include <iostream>
#include <string>
#include "move0.h"
int main()
{
using namespace std;
Move<int> origin, obj(0, 0);
int temp;
char ans='y';
int x, y;
cout<<"Origianl point: ";
origin.reset(1,1);
origin.showmove();
cout<<endl;
while ((ans!='q') and (ans!='Q'))
{
cout<<"Please enter the value to move x: ";
cin>>x;
cout<<"Please enter the value to move y: ";
cin>>y;
obj= obj.add(temp);
obj.showmove();
cout<<endl;
cout<<"Do you want to continue? (q to quit, r to reset): ";
cin>>ans;
if ((ans=='r') or (ans=='R'))
{
obj.reset(0, 0);
cout<<"Reset to origin: ";
obj.showmove();
cout<<endl;
}
}
return 0;
}
答案 0 :(得分:5)
嗯,我在猜测
int add(const Move & m) const;
应该是
Move add(const Move & m) const;
和类似的
template<typename Type>
int Move<Type>::add(const Move &m) const
应该是
template<typename Type>
Move<Type> Move<Type>::add(const Move &m) const
从错误消息中可以看出非常清楚。
答案 1 :(得分:4)
您的add
成员函数返回int:
int add(const Move & m) const;
但是你要返回一个Move
对象:
template<typename Type>
int Move<Type>::add(const Move &m) const
{
Move temp;
...
return temp;
}
没有从Move
转换为int
。您似乎想要返回Move
:
Move add(const Move & m) const;