【发布时间】:2015-11-19 03:48:30
【问题描述】:
我正在编写一个简单的 Int 类并使用运算符重载来使对象的行为方式与“int”类似。我已将整个程序分成 3 个文件,1)头文件:包含类声明 2)所有运算符重载函数的定义 3)包含 main 的测试文件 这三个在这里按顺序提到
#include <iostream>
using namespace std;
class Int
{
private:
int i;
public:
Int(): i(0) { }
Int(int in) : i(in) { }
void show() const
{
cout<<"value: "<<i<<endl;
}
Int operator +(const Int&) const;
Int operator -(const Int&) const;
Int operator *(const Int&) const;
Int operator /(const Int&) const;
//Int add(const Int&) const;
};
函数定义
#include <iostream>
#include <climits>
#include <cassert>
#include "int.h"
using namespace std;
typedef unsigned long long ull;
Int Int::operator +(const Int &i1) const
{
ull result;
result = i+ i1.i;
//cout<< result<<'\n';
if (result>INT_MAX)
{
cout<<"Out of int range.\n";
//assert(0);
}
else
return Int(int(result));
}
Int Int::operator -(const Int &i1) const
{
//typedef unsigned long long ull;
ull result;
result = i - i1.i;
//cout<< result<<'\n';
if (result < INT_MIN)
{
cout<<"Out of int range.\n";
//assert(0);
}
else
return Int(int(result));
}
Int Int::operator *(const Int &i1) const
{
//typedef unsigned long long ull;
ull result;
result = i* i1.i;
//cout<< result<<'\n';
if (result >INT_MAX)
{
cout<<"Out of int range.\n";
//assert(0);
}
else
return Int(int(result));
}
Int Int::operator /(const Int &i1) const
{
//typedef unsigned long long ull;
ull result;
result = i/ i1.i;
//cout<< result<<'\n';
if (result < INT_MIN)
{
cout<<"Out of int range.\n";
//assert(0);
}
else
return Int(int(result));
}
并用 main 测试程序:
#include <iostream>
#include "int.h"
int main(int argc, char const *argv[])
{
Int i1;
Int i2(4);Int i3(2);
i1 = i2 + i3;
i1.show();
i1 = i2 - i3;
i1.show();
i1 = i2 * i3;
i1.show();
i1 = i2 / i3;
i1.show();
return 0;
}
预期输出是:
Value : 6,
Value : 2,
value : 8
Value : 2.
但是我得到这样的输出:
value: 6
Out of int range.
value: 6
value: 8
Out of int range.
value: 8
我尝试了很多错误但无法找到的地方。 任何线索都会有很大帮助。
【问题讨论】:
-
顺便说一句,如果您希望您的课程尽可能像
int,只需使用一些其他方法,不要开始制作 + - 等,而是制作(非显式)int的强制转换运算符(除了您已经存在的另一个方向的构造函数) -
@vik14dec 乍一看,成员操作符 (
Int::operator + (const Int&)) 比独立版本 (friend Int operator + (const Int&, const Int&)) 更容易实现 - 我强烈建议尽可能选择独立版本。 .. -
你应该在
if分支中添加一个 throw 或 return 顺便说一句 -
Daniel Jour,我为此使用了“assert(0)”。只是为了检查输出,我对此进行了评论并在此处粘贴了代码。
标签: c++ class int operator-overloading