2013-04-20 99 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 

似乎從錯誤信息很清楚。

相關問題