Int类所保存的内容显然是可以进行算术运算的,因此对Int类进行算术运算符重载是一件非常自然的事情。
为Int类重载算术运算符,以普通函数的形式。
本关共3个文件,Int.h、Int.cpp和main.cpp。其中Int.h和main.cpp不得改动,用户只能修改Int.cpp中的内容。
Int.h内容如下:
#ifndef _INT_H_ //这是define guard
#define _INT_H_ //在C和C++中,头文件都应该有这玩意
class Int{
private://这是访问控制——私有的
int value; //这是数据成员,我们称Int是基本类型int的包装类,就是因为Int里面只有一个int类型的数据成员
public: //这是公有的
Int():value(0){}
Int(Int const&rhs):value(rhs.value){}
Int(int v):value(v){}
int getValue()const{return value;}
void setValue(int v){value=v;}
};//记住这里有一个分号
//算术运算符重载
Int operator + (Int const&lhs,Int const&rhs);
Int operator - (Int const&lhs,Int const&rhs);
Int operator * (Int const&lhs,Int const&rhs);
Int operator / (Int const&lhs,Int const&rhs);
Int operator % (Int const&lhs,Int const&rhs);
#endif
main.cpp内容如下
#include "Int.h"
#include <iostream>
using namespace std;
int main(){
int x,y;
cin>>x>>y;
Int a(x),b(y);
Int c,d,e,f,g;
c = a + b;
d = a - b;
e = a * b;
f = a / b;
g = a % b;
cout<<c.getValue()<<" "
<<d.getValue()<<" "
<<e.getValue()<<" "
<<f.getValue()<<" "
<<g.getValue()<<endl;
return 0;
}
我写的代码
Int Int::operator + (Int const&lhs,Int const&rhs){
Int temp;
temp.value=this->lhs.value+rhs.value;
return temp;
}
Int Int::operator - (Int const&lhs,Int const&rhs){
Int temp;
temp.value=lhs.value-rhs.value;
return temp;
}
Int Int::operator * (Int const&lhs,Int const&rhs){
Int temp;
temp.value=lhs.value*rhs.value;
return temp;
}
Int Int::operator / (Int const&lhs,Int const&rhs){
Int temp;
temp.value=lhs.value/rhs.value;
return temp;
}
Int Int::operator % (Int const&lhs,Int const&rhs){
Int temp;
temp.value=lhs.value%rhs.value;
return temp;
}
step1/Int.cpp:2:1: error: ‘Int’ does not name a type; did you mean ‘int’?
Int Int::operator + (Int const&lhs,Int const&rhs){
^~~
int
模板不是就是class名吗,不知道哪错了??请教。
Int.cpp
要包含头文件#include "Int.h"
,另外那些运算符是全局的,不是Int类里的,所以要去掉Int::
, this->
value是私有的,你不能直接访问啊