以下是main.h的内容
1#include <iostream>
2#include <string>
3using namespace std;
4
5class Sales_item
6{
7public :
8 Sales_item(string s,int num1,float price1);
9 Sales_item();
10 ~Sales_item(){}
11 Sales_item& operator =(const Sales_item& s1);
12 Sales_item& operator += (Sales_item& s1);
13 friend ostream& operator<<(ostream& out,const Sales_item& s1);
14 friend istream& operator>>(istream& in,Sales_item& s1);
15 friend bool operator ==(Sales_item& s1,Sales_item& s2); //friend是与操作数相同的
16 friend bool operator !=(Sales_item& s1,Sales_item& s2);
17 friend Sales_item operator +(Sales_item& s1,Sales_item& s2);
18 friend Sales_item operator -(Sales_item& s1,Sales_item& s2);
19private:
20 std::string isbn; //书目编号
21 int num; //书的数目
22 float total; //书的单价
23};
24
25Sales_item::Sales_item(string s, int num1, float price1)
26{
27 isbn = s;
28 num= num1;
29 total = price1;
30}
31Sales_item::Sales_item()
32{
33 isbn = ""; //赋值不同于初始化,这里是不能用括号初始化的
34 num = 0;
35 total = 0;
36}
37Sales_item& Sales_item::operator =(const Sales_item& s1) //类外部定义的时候总是没有加限定符
38{
39 this->isbn = s1.isbn;
40 this->num = s1.num;
41 this->total = s1.total;
42 return *this;
43}
44Sales_item& Sales_item::operator +=(Sales_item& s1)
45{
46 this->isbn += s1.isbn;
47 this->num += s1.num;
48 this->total += s1.total;
49 return *this;
50}
51ostream& operator<<(ostream& out,const Sales_item& s1) //类的外部就不能在用friend不允许位于类定义之外
52{
53 out << s1.isbn << "\t" << s1.num << "\t" << s1.total;
54 return out;
55}
56istream& operator>>(istream& in,Sales_item& s1)
57{
58 double price;
59 in >> s1.isbn >> s1.num >> price;
60 if (in)
61 s1.total = s1.num * price;
62 else
63 s1 = Sales_item();
64 return in;
65}
66bool operator ==(Sales_item& s1,Sales_item& s2)
67{
68 return s1.isbn==s2.isbn && s1.num==s2.num && s1.total==s2.total;
69}
70bool operator !=(Sales_item& s1,Sales_item& s2)
71{
72 return (s1.isbn!=s2.isbn)|| (s1.num!=s2.num)|| (s1.total!=s2.total);
73 /**//*return !(s1==s2);*/
74}
75Sales_item operator +(Sales_item& s1,Sales_item& s2)
76{
77 if (s1 == s2)
78 return Sales_item(s1.isbn,s1.num+s2.num,s1.total+s2.total);
79 else
80 return Sales_item();
81}
82Sales_item operator -(Sales_item& s1,Sales_item& s2)
83{
84 if (s1 == s2)
85 return Sales_item(s1.isbn,s1.num-s2.num,s1.total-s2.total);
86 else
87 return Sales_item();
88}
下面是main.cpp
:
1#include <iostream>
2#include "main.h"
3using namespace std;
4
5int main()
6{
7 Sales_item s1,s2;
8 cin >> s1 >> s2;
9 cout << s1 << endl << s2 << endl;
10 if (s1 == s2)
11 {
12 cout << "equal" << endl;
13 cout << s1+s2 << endl;
14 }
15 if (s1 != s2)
16 cout << "not equal" << endl;
17 return 0;
18}
当然,写这个代码的时候觉得很多问题都没有考虑清楚,不过最后还是解决了问题:
1.在书写过程中忘记了类型限定符。
2.细节问题。
3.函数的命名空间
现在我想说的是:
关于重载!=的时候遇到的问题,开始的时候我直接copy 了==的判断,所以直接就改成了!=相&&得形式,可想而知结果肯定是错误的。
因为判断不等于的时候,只要是一个不相等就不等,而如果用到了&&,那么即使有一个不等的话还是返回false,判定相等了,也就是
!=和==没有成为一个全集,两者不是互逆的关系。。
调试代码的技巧很重要啊!!
posted on 2009-09-27 14:15
deercoder 阅读(387)
评论(0) 编辑 收藏 引用 所属分类:
C/C++