- 43
- 0
- 约1.12万字
- 约 12页
- 2017-06-06 发布于河南
- 举报
实验2 运算符重载
实验二 运算符重载
一、实验目的
理解重载运算符的作用,学会对典型的运算符进行重载。
二、实验内容
(一)程序示例
1. 编写程序重载字符串运算符 + 、 分别用于字符串的拼接、比较运算,实现
字符串直接操作。其中: 运算符重载函数为友元函数,而 + 运算符重载
为成员函数。
#include iostream
#include string
using namespace std ;
class mystring
{
public:
mystring ( const char *str = NULL);
~mystring () {} // 析构函数
void display () {cout m_data endl;}
mystring operator + (const mystring s1);
friend int operator (const mystring s1, const mystring s2);
private:
char m_data [100]; // 用于保存字符串
};
mystring ::mystring (const char *str)
{
i (NULL == str)
{
*m_data = \0;
}
else
{
strcpy (m_data, str);
}
}
1
mystring mystring ::operator+ (const mystring s1)
{
mystring s;
strcpy (s.m_data,m_data);
strcat (s.m_data,s1.m_data);
return s;
}
int operator (const mystring s1, const mystring s2)
{
i (strcmp(s1.m_data, s2 .m_data) = 0)
return 1;
else
return 0;
}
int main ()
{
mystring s1 (Hello, ), s2 (world! ), s3;
s1 .display();
s2 .display();
s3 .display();
s3 = s1 + s2;
s3 .display();
cout (s1 s2) endl;
}
2. 编写一个矩形类 rect ,分别采用友元函数的方式重载和成员函数的方式重载
运算符 、 、==,用于比较两个矩形面积是否相等。
成员函数方法:
#include iostream
using namespace std;
class rect
{
public:
rect (float i = 0, float j = 0) {length = i; width = j;}
~rect() {}
void area () {cout length * width endl;}
int operator == (rect r);
int operator (rect r);
int operator (rect r);
private:
2
float length;
float width;
};
int rect ::operator == (rect r)
{
i ((length * w
您可能关注的文档
最近下载
- 2025年安徽省普通高校对口招生考试(英语)历年参考题库含答案详解.docx VIP
- JIS D5301-2006(中文版本).pdf VIP
- 2025年安徽省普通高校对口招生考试(语文)历年参考题库含答案详解.docx VIP
- 2025年安徽省普通高校对口招生考试(计算机类)历年参考题库(含答案).docx VIP
- 完美演练新概念英语练习1上 参考答案.docx VIP
- 2026年安徽省普通高校对口招生考试(英语)历年参考题库含答案详解.docx VIP
- AP统计学 2015年真题 附答案和评分标准 AP Statistics 2015 Real Exam with Answers and Scoring Guidelines.pdf VIP
- 2026年安徽省普通高校对口招生考试(语文)历年参考题库含答案详解.docx VIP
- 2023年安徽省滁州市小升初语文试卷(含答案).docx VIP
- iCloud邮箱账号密码如何找回.docx VIP
原创力文档

文档评论(0)