c++初学者,哪位大神能够帮我看下这个程序,编译没有问题,但是运行结果不对,顺便说下怎么在这里重载<<
#include<iostream>usingnamespacestd;classNumber{protected:ints;intx;inty;public:boolo...
#include <iostream>
using namespace std;
class Number
{
protected:
int s;
int x;
int y;
public:
bool operator > (const Number &r1)
{
return (s > r1.s);
}
bool operator < (const Number &r2)
{
return (s < r2.s);
}
};
void mysort(Number *numArray[], int len)
{
int i = 0, j = 0;
for( i = 0; i < len - 1; ++i)
for( j = 0; j < len - i - 1; j ++)
if( *numArray[j] > *numArray[j + 1])
{
Number *temp;
*temp = *numArray[j];
*numArray[j] = *numArray[j + 1];
*numArray[j + 1] = *temp;
}
}
//整型类
int RETURN_INT(int x)
{
return x;
}
class IntNumber : public Number
{
int a;
public:
IntNumber(int x)
{
a = x;
RETURN_INT(a);
}
};
bool UT_Number_01 ()
{
Number* array[3] = {new IntNumber(3), new IntNumber(2), new IntNumber(1)};
mysort(array, 3);
return ((*array[0]) < (*array[1])) && ((*array[1]) < (*array[2]));
}
int main()
{
if(UT_Number_01())
cout << "ture" << endl;
else
cout << "false" << endl;
return 0;
} 展开
using namespace std;
class Number
{
protected:
int s;
int x;
int y;
public:
bool operator > (const Number &r1)
{
return (s > r1.s);
}
bool operator < (const Number &r2)
{
return (s < r2.s);
}
};
void mysort(Number *numArray[], int len)
{
int i = 0, j = 0;
for( i = 0; i < len - 1; ++i)
for( j = 0; j < len - i - 1; j ++)
if( *numArray[j] > *numArray[j + 1])
{
Number *temp;
*temp = *numArray[j];
*numArray[j] = *numArray[j + 1];
*numArray[j + 1] = *temp;
}
}
//整型类
int RETURN_INT(int x)
{
return x;
}
class IntNumber : public Number
{
int a;
public:
IntNumber(int x)
{
a = x;
RETURN_INT(a);
}
};
bool UT_Number_01 ()
{
Number* array[3] = {new IntNumber(3), new IntNumber(2), new IntNumber(1)};
mysort(array, 3);
return ((*array[0]) < (*array[1])) && ((*array[1]) < (*array[2]));
}
int main()
{
if(UT_Number_01())
cout << "ture" << endl;
else
cout << "false" << endl;
return 0;
} 展开
1个回答
展开全部
有几个地方有问题:
1.Number没有带参数的构造函数,而事实上要用到。在class Number定义中加入
Number(int x=0):s(x){ }
2.mysort函数写错了。如果我没理解错,原代码是想用插入排序由小到大地排?
void mysort(Number* numArray[], int len)
{
int i = 0, j = 0;
for( i = 1; i <= len - 1; ++i)
for( j = i; j > 0; --j)
if( *numArray[j] < *numArray[j - 1])
{
Number *temp;
temp = numArray[j];
numArray[j] = numArray[j - 1];
numArray[j - 1] = temp;
}
}
而且,交换的时候应该换指针吧。
3.你在IntNumber中重新引入了一个私有成员a,而operator<针对的是成员s,你的a其实没用,可以注掉,应该调用基类的构造函数。
class IntNumber : public Number
{
int a;
public:
IntNumber(int x): Number(x)
{
a = x;
RETURN_INT(a);
}
};
这样应该可以了(我只发现了这么多)
追问
原题里面还有一个float型的,我该怎么写构造函数
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询