C++无法将'classname<int>'转换为'int'作为回报
C++ cannot convert 'classname<int>' to 'int' in return
我正试图将模板应用到原始的类程序中。但我得到的错误不能隐蔽的"移动"到"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;
}
没有从Move
到int
的转化。您可能想要返回Move
:
Move add(const Move & m) const;
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- EASTL矢量<向量<int>>连续的
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- 'structstd::对<int,int>'没有名为'push_back'