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;
    }
    else
        r = 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 !";
    else
        cout << "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.1416

using 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 Constructor
    polar(float r1, float  a1); // defined constructor
    polar operator+(polar r1);  // overload + operator
    void display();
};

polar::polar(float r1, float a1)
{
    r = r1;
    a = a1 * (PI/180);  // convert value into angle; 1° = PI /180 rad , 1 rad = 180°/PI
    x = 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引用时,这种构造函数称为转换构造函数。 转换构造函数是对构造函数的重载。(后面专门写一篇关于转换构造函数的文章。)

  • 19
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值