gpt4 book ai didi

c++ - Int类型类的运算符重载

转载 作者:行者123 更新时间:2023-11-30 01:47:02 25 4
gpt4 key购买 nike

我正在编写一个简单的 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

我尝试了很多错误的地方,但找不到。任何线索都会有很大帮助。

最佳答案

问题是无符号值与有符号值的比较:

if (result < INT_MIN)

更根本的是,当您想像一个带符号的 int 时,为什么您希望结果是 unsigned long long

我明白你为什么要使用 long long 来检查 int 操作的范围(虽然这样做不是完全可移植的)但是选择 unsigned 似乎只是一个错误。

关于c++ - Int类型类的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32204020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com