2013-04-20 96 views
-3

我试图将模板应用到原始类程序中。但是我得到了错误,无法将“移动”转换为“int”作为回报。请帮忙....C++无法将'类名称<int>'转换为'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; 
} 
+6

为什么使用'template'-s?你似乎并不需要它们。模板是用于通用编程的,定义模板不适用于初学C++程序员.... – 2013-04-20 07:42:16

回答

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; 
} 

没有转换,从Moveint。您可能想要返回Move

Move add(const Move & m) const; 
+1

感谢它的完美运作。 – user2301576 2013-04-20 08:05:11

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 

似乎从错误信息很清楚。

相关问题