C++无法将'classname<int>'转换为'int'作为回报

C++ cannot convert 'classname<int>' to 'int' in return

本文关键字:int gt 转换 回报 classname C++ lt      更新时间:2023-10-16

我正试图将模板应用到原始的类程序中。但我得到的错误不能隐蔽的"移动"到"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;
}

我猜

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

从错误信息中似乎很清楚

您的add成员函数返回int:

int add(const Move & m) const;

但是你返回的是一个Move对象:

template<typename Type> 
int Move<Type>::add(const Move &m) const
{
    Move temp;
    ...
    return temp;
}

没有从Moveint的转化。您可能想要返回Move:

Move add(const Move & m) const;