-3

我正在尝试将模板应用到原始类程序中。但是我得到了不能将'Move'转换为'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;
}
4

2 回答 2

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

从错误消息中似乎很清楚。

于 2013-04-20T07:41:24.343 回答
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;
于 2013-04-20T07:41:31.727 回答