C++ 基础练习 - Chapter 7 (英文版)

Review Questions:

7.1 What is operator overloading?

Answer:

The mechanism of giving special meaning to an operator is known as operator overloading.

7.2 Why is it necessary to overloading an operator?

Answer:

We can almost create a new language of our own by the creative use of the function and operator overloading techniques.

7.3 What is an operator function? Describe the syntax of an operator function.

Answer:

To difine an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. By which function this is done, is called operator function.

Syntax of operator function:

return-type class-name::operator OP (argument list)
{function body  // task defined
}

7.4 How many arguments are required in the definition of an overloaded unary operator (一元运算符)?

Answer:

No argument are needed.

7.5 A class alpha has a constructor as follows:

alpha(int a, double b);

Can we use this constructor to convert types?

Answer:

No. The constructors used for the type conversion take a single argument whose type is to be converted.

7.6 What is a conversion function? How is it created? Explain its syntax.

Answer:

C++ allows us to define an overloaded casting operator that could be used to convert a class type data to a basic type. This is referred to conversion function.

Syntax:

Operator type name()
{(Function Statements)
}

7.7 A friend function cannot be used to overload the assignment operator = . Explain why?

Answer:

A friend function is a non-member function of the class to which it has been defined as friend. Therefore it just uses the functionality (functions and data) of the class. So it does not consist the implementation for that class. That’s why it cannot be used to overload the assignment operator.

7.8 When is a friend function compulsory? Give an example.

Answer:

When we need to use two different type of operands for a binary operator, then we must use friend function.

**Example : **

A = B + 3;
or
A = B * 2;  is valid.
But A = 2 + B; or A = 2 * B; will not work.

Because the left hand operand is responsible for invoking the member function. In this case friend function allows both approaches.

以下两种情况需要使用友元函数:
(1)运算符重载的某些场合;
(2)两个类需要共享数据的时候。

7.9 We have two classes X and Y. If a is an object of X and b is an object of Y and we want to say a = b; What type of conversion routine should be used and where?

Answer:

We have to use one class to another class type conersion. The type-conversion function to be located in the source class or in the destination class.

7.10 State whether the following statements are TRUE or FALSE.

a. Using the operator overloading concept, we can change the meaning of an operator.

b. Operator overloading works when applied to class object only.

c. Friend functions cannot be used to overload operators.

d. When using an overloaded binary operator, the left operand is implicitly passed to the member function.

e. The overloaded operator must have at least one operand that is use-defined type.

f. Operator functions never return a value.

g. Through operator overloading, a class type data can be converted to a basic type data.

h. A constructor can be used to convert a basic type to a class type data.

Answer:

a. FALSE,

运算符的重载有以下几点需要注意:
1.不是所有的运算符都能被重载。
2.重载不能改变运算符的优先级和结合性。
3.重载不会改变运算符的用法,原有有几个操作数、操作数在左边还是在右边,这些都不会改变。
4.运算符重载函数不能有默认的参数。
5.运算符重载函数既可以作为类的成员函数,也可以作为全局函数。
6.箭头运算符->、下标运算符[ ]、函数调用运算符( )、赋值运算符=只能以成员函数的形式重载。

b. TRUE; c. FALSE; d. FALSE; e. TRUE; f. FALSE; g. TRUE; h. TRUE

Explian h:
A conversion constructor is a single-parameter constructor that is declared without the function specifier explicitly. The compiler uses conversion constructors to convert objects from the type of the first parameter to the type of the conversion constructor’s class.

Conversion Constructors: There are constructors that convert types of its parameter into a type of the class. The compiler uses these constructors to perform implicit class-type conversions. These conversions are made by invoking the corresponding constructor with matches the list of values/objects that are assigned to the object.
Example 1 :

#include <iostream>class MyClass {int a, b;public:MyClass(int i){a = i;b = i;}void display(){std::cout << " a = " << a << " b = " << b << "\n";}
};int main()
{MyClass object(10);object.display();// Single parameter conversion constructor is invoked.object = 20;object.display();return 0;
}

Example 2 :

#include <iostream>class MyClass {int a, b;public:MyClass(int i, int y){a = i;b = y;}void display(){std::cout << " a = " << a << " b = " << b << "\n";}
};int main()
{MyClass object(10, 20);object.display();// Multiple parameterized conversion constructor is invoked.object = { 30, 40 };object.display();return 0;
}

Debugging Exercises:

7.1 Identify the error in the following program.

#include <iostream>
using namespace std;class Space
{private:int mCount;public:Space(){mCount = 0;}Space operator ++(){mCount++;return Space(mCount);}
};int main()
{Space objSpace;objSpace.operator++();return 0;
}

Answer:

The argument of Space() function is void type, so when this function is called there are no argument can send to it. But “mCount” argument is sending to Space() function through return Space(mCount); statement.

conrrection:

return Space(mCount);replaced by return Space();

7.2 Identify the error in the following program.

#include <iostream>
using namespace std;enum WeekDays
{mMonday, mTuesday, mWednesday, mThursday, mFriday, mSaturday, mSunday
};void op==(WeekDays &w1, WeekDays &w2)
{if(w1==mMonday && w2==mMonday){cout << "Same Day." << endl;}else{cout << "Different Day !" << endl;}
}int main()
{WeekDays w1 = mMonday, w2 = mMonday;operator==(w1, w2);return 0;
}

Answer:

Have to change the function name to:

void operator==(WeekDays &w1, WeekDays &w2)

Programming Exercises:

7.1 Define a class string. Use overload == operator to compare two strings.

#include <iostream>
#include <cstring>
using namespace std;class String
{
private:char str[1000];public:void input(){gets(str);}int operator==(String s2);
};int String::operator==(String s2)
{int r = strcmp(str, s2.str);if(r == 0){r = 1;}elser = 0;return r;
}int main()
{String s1, s2;cout << "Enter 1st string : ";s1.input();cout << "Enter 2nd string : ";s2.input();if(s1 == s2)cout << "Two strings are equal !";elsecout << "Two string are NOT equal !";return 0;
}

7.2 Create a class MyFloat that contains one flozt data member. Overload all the four arithmetric operators so that they operate on the objects of MyFloat.

Answer:

#include <iostream>
using namespace std;class MyFloat
{
private:float data;public:MyFloat(){};MyFloat(float d) {data = d;}MyFloat operator+(MyFloat f1);MyFloat operator-(MyFloat f2);MyFloat operator*(MyFloat f3);MyFloat operator/(MyFloat f4);void display();
};MyFloat MyFloat::operator+(MyFloat f1)
{MyFloat temp;temp.data = data + f1.data;return (temp);}
MyFloat MyFloat::operator-(MyFloat f2)
{MyFloat temp;temp.data = data - f2.data;return (temp);
}MyFloat MyFloat::operator*(MyFloat f3){MyFloat temp;temp.data = data * f3.data;return (temp);
}MyFloat MyFloat::operator/(MyFloat f4)
{MyFloat temp;temp.data = data / f4.data;return (temp);
}void MyFloat::display()
{cout << data << endl;
}int main()
{MyFloat F1, F2, F3, F4, F5, F6;F1 = MyFloat(2.5);F2 = MyFloat(3.2);F3 = F1 + F3;F4 = F2 - F1;F5 = F1 * F2;F6 = F2 / F1;cout << "F1 = ";F1.display();cout << "F2 = ";F2.display();cout << "F1 + F2 = ";F3.display();cout << "F2 - F1 = ";F4.display();cout << "F1 * F2  = ";F5.display();cout << "F2 / F1 = ";F6.display();return 0;
}

7.3 Use conversion routine to convert from Polar system to Rectangular system.

Answer:

#include <iostream>
#include <cmath>
#define PI 3.1416using namespace std;class ConversionPoint
{
private:float x, y, r, theta;public:void set_xy();void set_r_theta();void show_xy();void show_r_theta();void conversion(int t);
};void ConversionPoint::set_xy()
{cout << "Enter the value of x & y : ";cin >> x >> y;
}void ConversionPoint::set_r_theta()
{cout << "Enter the value of r & theta : ";cin >> r >> theta;
}void ConversionPoint::show_xy()
{cout << "CERTECIAN Form: \n"<< " x = " << x << "\n"<< " y = " << y << endl;
}void ConversionPoint::show_r_theta()
{cout << "Polar Form: \n"<< " r = " << r << "\n"<< " theta = " << theta * (180/PI) << " degree." << endl;
}void ConversionPoint::conversion(int t)
{if(t == 1){r = sqrt(x*x + y*y);if(x!=0){theta = atan(y/x);show_r_theta();}else{cout << "POLAR FORM : \n"<< " r = " << r << "\n"<< " theta = 90 degree \n";}}else if(t == 2){x = r * cos(theta);y = r * sin(theta);show_xy();}
}int main()
{ConversionPoint coord;int test;cout << "Press 1 to input certecian point \n"<< "Press 2 to input polar point \n"<< "What is your input? : ";cin >> test;if(test == 1)coord.set_xy();else if(test == 2)coord.set_r_theta();coord.conversion(test);return 0;
}

7.4 Design a class Polar which describes a point in the plane using polar coordinates radius and angle. A point in polar coordinates is shown below.

Use the overload + operator to add two objects of polar. Note that we cannot add polar values of two points directly. This requires first the conversion of points into rectangular coordinates, then adding the respective rectangular coordinates and finally converting the result back into polar coordinates. You need to use the following trigonometric formula(三角公式):

x = r * cos(a);

y = r * sin(a);

a = atan(y / x); // arc tangent

r = sqrt(x * x + y * y)

在这里插入图片描述

Answer:

#include <iostream>
#include <cmath>
#define PI 3.1416
using namespace std;class polar
{
private:float x, y, r, a;public:polar(){};  // Default Constructorpolar(float r1, float  a1); // defined constructorpolar operator+(polar r1);  // overload + operatorvoid display();
};polar::polar(float r1, float a1)
{r = r1;a = a1 * (PI/180);  // convert value into angle; 1° = PI /180 rad , 1 rad = 180°/PIx = r * cos(a);y = r * sin(a);
}polar polar::operator+(polar r1)
{polar R;R.x = x + r1.x;R.y = y + r1.y;R.r = sqrt(R.x * R.x + R.y * R.y);R.a = atan(R.y/R.x);return R;
}void polar::display()
{cout << "radius = " << r << "\n angle = " << a * (180/PI) << endl;
}int main()
{polar p1, p2, p3;float r, a;cout << "Enter radius and angle : ";cin >> r >> a;p1 = polar(r, a);p2 = polar(8, 45);p3 = p1 + p2;cout << " p1 : \n";p1.display();cout << " p2 : \n";p2.display();cout << " p3 : \n";p3.display();return 0;
}

Conclusion:

转换构造函数(conversion constructor function) 的作用是将一个其他类型的数据转换成一个类的对象。 当一个构造函数只有一个参数,而且该参数又不是本类的const引用时,这种构造函数称为转换构造函数。 转换构造函数是对构造函数的重载。(后面专门写一篇关于转换构造函数的文章。)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1489356.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

33.【C语言】实践扫雷游戏

预备知识&#xff1a; 第13篇 一维数组 第13.5篇 二维数组 第28篇 库函数 第29篇 自定义函数 第30篇 函数补充 0x1游戏的运行&#xff1a; 1.随机布置雷 2.排雷 基本规则&#xff1a; 点开一个格子后&#xff0c;显示1&#xff0c;对于9*9&#xff0c;代表以1为中心的去…

UDP网口(3)逻辑组包(下)

文章目录 1.ARP应答验证2.UDP实现思路3.UDP接收验证4.UDP发送验证5.总结与思考6.传送门 1.ARP应答验证 创建一个ARP应答工程&#xff0c;当PC发出ARP请求的时候&#xff0c;手动按下板卡指定按键&#xff0c;将会响应ARP应答。以此验证phy芯片的配置正常&#xff0c;硬件链路正…

【Emacs有什么优点,用Emacs写程序真的比IDE更方便吗?】

&#x1f3a5;博主&#xff1a;程序员不想YY啊 &#x1f4ab;CSDN优质创作者&#xff0c;CSDN实力新星&#xff0c;CSDN博客专家 &#x1f917;点赞&#x1f388;收藏⭐再看&#x1f4ab;养成习惯 ✨希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出…

mfc100u.dll 文件缺失?两种方法快速修复丢失mfc100u.dll 文件难题

您的电脑是否遭遇了 mfc100u.dll 文件缺失的问题&#xff1f;这种情况通常由多种原因引起。在本文中&#xff0c;我们将介绍两种修复 mfc100u.dll 文件丢失问题的策略——一种是手动方法&#xff0c;另一种是自动修复的使用。我们将探讨如何有效地解决 mfc100u.dll 文件缺失的几…

CAS算法

CAS算法 1. CAS简介 CAS叫做CompareAndSwap&#xff0c;比较并交换&#xff0c;主要是通过处理器的指令来保证操作的原子性。 CAS基本概念 内存位置 (V)&#xff1a;需要进行CAS操作的内存地址。预期原值 (A)&#xff1a;期望该内存位置上的旧值。新值 (B)&#xff1a;如果旧…

Prometheus各类监控及监控指标和告警规则

目录 linux docker监控 linux 系统进程监控 linux 系统os监控 windows 系统os监控 配置文件&告警规则 Prometheus配置文件 node_alert.rules docker_container.rules mysql_alert.rules vmware.rules Alertmanager告警规则 consoul注册服务 Dashboard JSON…

(8) ubuntu ROS 安装

文章目录 安装流程1. 进入ros官网2. 根据自己ubuntu系统选择版本&#xff08;我是20.04的ubuntu&#xff09;3.根据流程开始安装3.1 设置sources.list 4.验证ros5.安装rosdep 安装流程 1. 进入ros官网 https://www.ros.org/ 2. 根据自己ubuntu系统选择版本&#xff08;我是2…

排查C++软件异常的常见思路与方法(实战经验总结)

目录 1、概述 2、常用的C++异常排查思路与方法 2.1、IDE调试 2.1.1、Debug和Release下的调试 2.1.2、VS附加到进程调试 2.1.3、Windbg附加到进程调试 2.2、添加日志打印 2.3、分块注释代码 2.4、数据断点 2.5、历史版本比对法 2.6、Windbg静态分析与动态调试 2.6.1…

如何发现快速发现分析生产问题SQL

Performance Schema介绍 Performance Schema提供了有关MySQL服务器内部运行的操作上的底层指标。为了解释清楚Performance Schema的工作机制&#xff0c;先介绍两个概念。 第一个概念是程序插桩&#xff08;instrument&#xff09;。程序插桩在MySQL代码中插入探测代码&#xf…

Hadoop单机版环境搭建

一 . 案例信息 Hadoop 的安装部署的模式一共有三种&#xff1a; 本地模式&#xff0c;默认的模式&#xff0c;无需运行任何守护进程&#xff08; daemon &#xff09;&#xff0c;所有程序都在单个 JVM 上执行。由 于在本机模式下测试和调试 MapReduce 程序较为方便&#x…

鸿蒙开发——axios封装请求、拦截器

描述&#xff1a;接口用的是PHP&#xff0c;框架TP5 源码地址 链接&#xff1a;https://pan.quark.cn/s/a610610ca406 提取码&#xff1a;rbYX 请求登录 HttpUtil HttpApi 使用方法

PHP8.3.9安装记录,Phpmyadmin访问提示缺少mysqli

ubuntu 22.0.4 腾讯云主机 下载好依赖 sudo apt update sudo apt install -y build-essential libxml2-dev libssl-dev libcurl4-openssl-dev pkg-config libbz2-dev libreadline-dev libicu-dev libsqlite3-dev libwebp-dev 下载php8.3.9安装包 nullhttps://www.php.net/d…

基于Qt的视频剪辑

在Qt中进行视频剪辑可以通过多种方式实现&#xff0c;但通常需要使用一些额外的库来处理视频数据。以下是一些常见的方法和步骤&#xff1a; 使用FFmpeg FFmpeg是一个非常强大的多媒体框架&#xff0c;可以用来处理视频和音频数据。你可以使用FFmpeg的命令行工具或者其库来实现…

Github 2024-07-26 Java开源项目日报 Top10

根据Github Trendings的统计,今日(2024-07-26统计)共有10个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量Java项目9HTML项目1TypeScript项目1非开发语言项目1JavaGuide - Java 程序员学习和面试指南 创建周期:2118 天开发语言:Java协议类型:Apache…

springboot使用Gateway做网关并且配置全局拦截器

一、为什么要用网关 统一入口&#xff1a; 作用&#xff1a;作为所有客户端请求的统一入口。说明&#xff1a;所有客户端请求都通过网关进行路由&#xff0c;网关负责将请求转发到后端的微服务 路由转发&#xff1a; 作用&#xff1a;根据请求的URL、方法等信息将请求路由到…

C#初级——枚举

枚举 枚举是一组命名整型常量。 enum 枚举名字 { 常量1, 常量2, …… 常量n }; 枚举的常量是由 , 分隔的列表。并且&#xff0c;在这个整型常量列表中&#xff0c;通常默认第一位枚举符号的值为0&#xff0c;此后的枚举符号的值都比前一位大1。 在将枚举赋值给 int 类型的…

java计算机毕设课设—记账管理系统(附源码和安装视频)

这是什么系统&#xff1f; java计算机毕设课设—记账管理系统&#xff08;附源码和安装视频&#xff09; 记账管理系统主要用于财务人员可以从账务中判断公司的发展方向。对个人和家庭而言&#xff0c;通过记账可以制定日后的 消费计划&#xff0c;这样才能为理财划出清晰合理…

Scrapy 爬取旅游景点相关数据(三)

这一节我们将之前爬取到的景点数据进行解析&#xff0c;并且保存为excel&#xff0c;便于后续使用&#xff0c;本节包含 &#xff08;1&#xff09; 景点数据解析 &#xff08;2&#xff09;数据保存到excel 1 编写爬虫 这次继续改进第二节的爬虫&#xff0c;新建一个爬虫文…

【Java基础】动态代理与代理模式哪些事儿

文章目录 代理静态代理动态代理基于接口的jdk动态的demo源码解析Proxy.newProxyInstancejdk 动态的生成的字节码 基于父类的cglib动态代理源码解析 代理设计模式应用场景 Spring AOP小结 代理 代理其实就是扩展目标对象的功能&#xff0c;比如普通人不具备超人能力&#xff0c…

青少年绘画大赛兰州站:童梦起航 致敬科学 续写降压0号之父强国梦

2024年7月21日&#xff0c;“鹤舞童梦致敬科学精神”青少年绘画大赛在兰州隆重启幕。 活动邀请了多位重量级嘉宾担任评委&#xff0c;包括中国美术家协会会员、甘肃省油画协会常务理事马爱兵&#xff0c;兰州交通大学天佑美术馆馆长王欣&#xff0c;以及国家一级美术师蔡晓斌。…