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

Review Question:

8.1 What does inheritance mean in C++?

Answer:

The mechanism of deriving a new class from an old one is called inheritance. The old class is referred to as the base class and the new one is called derived class.

8.2 What are the different forms of inheritance? Give an example for each.

Answer:

1. Single inheritance: Only one derived class inherited from only one base class is called single inheritance. Example:

class A{... ...};
class B: public A{... ...};

2. Multiple inheritance: a class can inherit the attributes of two or more classes. Example: class D: visibility B1, B2 and B3.(visibility may be public or private)

在这里插入图片描述

{
	(body of D)
}

3. Multilevel inheritance: a class is derived from a base class, and another class is derived from this derived class and so on, then it’s called multilevel inheritance. Example:

在这里插入图片描述

class A {... ... };
class B: public A {... ...};
class C: private B {... ...};

4. Hierarchical inheritance: the inheritance follows the hierarchical design of a program, then it;s called hierarachical inheritance. Example:

在这里插入图片描述

class student {... ...};
class Arts: public student {... ...};
class Medical: public student {... ...};
class Engineering: public student {... ...};
class CSE: public Engineering {... ...};
class EEE: public Engineering {... ...};
class ECE: public Engineering {... ...};

5. Hybrid inheritance: when multi level and multi inheritances are applied to an inheritance, then it’s calledhybrid inheritance. Example:

在这里插入图片描述

class student {... ...};
class test: public student {... ...};
class result: public test{... ...};
class result: publice sports{... ...};

8.3 We know that a private member of a base class is not inheritable. Is it anyway possible for the objects of a derived class to access the private members of the base class? If yes, how? Remember, the base class cannot be modified.

Answer:

Yes. It’s possible for the objects of derived class to access the private member of the base class by a member function of base class which is public. Example:

#include <iostream>
using namespace std;

class B
{
private:
    int a;
    
public:
    int get_a();
    void set_a();
};

class D: public B
{
private:
    int b;

public:
    void display_a();
};

void D::display_a()
{
    cout<< " a = " << get_a()<<'\n';
}

void B::set_a()
{
    a = 383;
}

int B::get_a()
{
    return a;
}

int main()
{
    D d;
    d.set_a();
    d.display_a();
    
    return 0;
}

8.4 When do we use the protected visibility specifier to a class member?

Answer:

When we want access a data member by the member function within its class and by the member functions immediately derived from it, then we use visibility modifier protected.

8.5 When do we make a class virtual?

Answer:

To avoid the douplication of inherited members due to multiple paths between base and derived classes we make base class virtual.

8.6 In what order are the class constructors called when a derived class object is created?

Answer:

According to the order of derived class header lines.

8.7 Class D is derived from class B. The class D does not contain any data members of its own. Does the class D required constructors? If yes, why?

Answer:

D doesn’t required any constructor or because a default constructor is always set to class by default.

8.8 What is containership? How does it differ from inheritance?

Answer:

Containership is another word for composition. That’s the “has-a” relationship where A “has-a” member that is an object of class B.

Difference: Inheritance the derived class inherits the member data and function from the base class and can manipulatebase public/protected member data as tis own data. By default a program which constructs a derived class can directly access the public members of the base class as well. The derived class can be safely down cast to the base class, because the derived “is-a” base class.

Container: a class contain another object as member data. The class which contains the object cannot access any protected or private members of the contained class (unless the container it was made a friend in the definition of the contained class). The relationship between the container and the contained object is “has-a” instead of “is-a”.

8.9 Describe how an object of a class that contains objects of other classes created?

Answer:

By inheriting an object can be create that contains the objects of other class. Example:

class A
{
private:
	int a;
public:
void doSomething();
};

class B: class A
{
private:
	int b;
public:
	void doNothing();
};
/* Now if object of B is created, then it contains:
1. void doSomething();
2. int b;
3. void doNothing(); */

8.10 State whether the following statements are TRUE or FALSE:

a. Inheritance helps in making a general class into a more specifuc class.

b. Inheritance aids data hiding.

c. One of the advantages of inheritance is that it provides a conceptual framework.

d. Inheritance facilitates the creations of class libraries.

e. Defining a derived class requires some changes in the base class.

f. A base class is never used to create object.

g. It’s legal to have an object of one class as a member of another class.

h. We can prevent the inheritance of all members of the base class by making base class virtual in the definition of the derived class.

Answer:

TRUE, FLASE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE.

Debugging Exercises:

8.1 Identify the error in the following program.

#include <iostream>
using namespace std;

class A
{
public:
    A() {cout << "A";}
};

class B: public A
{
public:
    B() {cout << "B";}
};

class C: public B
{
public:
    C() {cout << "C";}
};

class D
{
public:
    D() {cout << "D";}
};

class E: public C, public D
{
public:
    E() {cout << "E";}
};

class F: public B, virtual E
{
public:
    F() {cout << "F";}
};

int main()
{
    F f;
    return 0;
}

Answer:

warning: direct base ‘B’ inaccessible in ‘F’ due to ambiguity.

8.2 Find errors in the following program. State reasons.

#include <iostream>
using namespace std;

class X
{
private:
    int x1;
protected:
    int x2;
public:
    int x3;
};

class Y: public X
{
public:
    void f() 
    {
        int y1, y2, y3;
        y1 = x1;
        y2 = x2;
        y3 = x3;
    }
};

class Z: X
{
public:
    void f() 
    {
        int z1, z2, z3;
        z1 = x1;
        z2 = x2;
        z3 = x3;
    }
};

int main()
{
    int m, n, p;
    Y y;
    m = y.x1;
    n = y.x2;
    p = y.x3;
    
    Z z;
    m = z.x1;
    n = z.x2;
    p = z.x3;
    
    return 0;
}

Answer:

Here x1 is private, so x1 cannot be inherited.

// Those are all not valid
y1 = x1;
z1 = x1;
m = y.x1;
m = z.x1;

8.3 Debug the following program.

#include <iostream>
using namespace std;

class B1
{
private:
    int b1;
public:
    void display() {cout << "b1 : " << b1 << "\n";}
};

class B2
{
private:
    int b2;
public:
    void display() {cout << "b2 : " << b2 << "\n";}
};

class D: public B1, public B2
{
    // Nothing here
};

int main()
{
    D d;
    d.display();
    d.B1::display();
    d.B2::display();
    
    return 0;
}

Answer:

d.display(); -----> error: request for member ‘display’ is ambiguous.

Programming Exercises:

8.1 Assume that a bank maintains two kinds of customer accounts , one called savings and the other as current accounts. The savings account provides compound interest and withdrawal facilities but no chequebook facility. The current account provides a chequebook facility but no interest. Current account holders should also maintain a minimum balance and if the balance falls below this level a service charge is imposed.

create a class account that stores customer name, account number and type of account. From this derive the classes cur_acct and sav_acct to make them more specific to their requirements. Include necessary member functions in order to achieve the following tasks:

a. Accept the deposit from a customer and update the balance.

b. Display the balance.

c. Compute and deposit interest.

d. Permit withdraw and update the balance.

e. Check for the minimum balance, impose a penalty, necessary and update the balance.

Do not use any constructors. Use member functions to initialize class members.

#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;

#define minimum 500
#define service_charge 100
#define rate 0.15

class account
{
private:    //protected
    char name[100];
    int acc_number;
    char acc_type[100];

public:
    void create(char *t);
};

void account::create(char *t)
{
    cout << " Enter customer name : ";
    gets(name);
    strcpy(acc_type, t);
    cout << " Enter account number : ";
    cin >> acc_number;
}

// current account
class cur_account: public account
{
private:
    float balance;

public:
    void deposit(float d);
    void withdraw(float w);
    void display();

};

void cur_account::deposit(float d)
{
    balance = d;
}

void cur_account::withdraw(float w)
{
    if(balance < w)
        cout << " Sorry, your balance is less than your withdrawal amount \n";
    else
    {
        balance -= w;
        if(balance < minimum)
        {
            cout << "\n your current balance is : " << balance
                 << " Which is less than Minimum" << minimum
                 << " your account is discharged by : " << service_charge;

            int test;
            cin >> test;
            if(test == 0)
            balance += w;
        }
    }
}

void cur_account::display()
{
    cout << "\n Now Balance = " << balance <<endl;
}

// Saving account
class sav_account: public account
{
private:
    float balance;
    int d, m, y;
public:
    void deposit(float d);
    void withdraw(float w);
    void display();
    void interest();
    void setDate(int a, int b, int c){d=a;m=b;y=c;}
};

void sav_account::deposit(float d)
{
    int x, y, z;
    cout << " Enter today's date (day,month,year) : ";
    cin >> x >> y >> z;

    setDate(x,y,z);
    balance = d;
}
void sav_account::withdraw(float w)
{
    if(balance < w)
        cout << " Sorry, your balance is less than your withdrawal amount \n";
    else
    {
        balance -= w;
        if(balance < minimum)
        {
            cout << "\n your current balance is : " << balance
                 << " Which is less than Minimum" << minimum
                 << " your account is discharged by : " << service_charge;

            int test;
            cin >> test;
            if(test == 0)
            balance += w;
        }
    }
}

void sav_account::display()
{
    cout << " \n Now Balance = " << balance;
}

// 利息按照每月30, 每年365 天计算
void sav_account::interest()
{
    int d1, m1, y1;

    cout << " Enter today's date (day,month,year) : ";
    cin >> d1>>m1>>y1;

    float dur_year;
    int dur_day, dur_mon;
    dur_day = d1 - d;
    dur_mon = m1 - m;
    dur_year = float((dur_day + dur_mon*30)/365.0 + (y1 - y));

    cout << "dur_day = " << dur_day << ",dur_mon = " << dur_mon << ",dur_year = " << dur_year<<endl;

    float intrst;
    intrst = balance * rate * dur_year; // 利息 = 本金 * 利息 * 存期
    cout << "Interest is : " << intrst << endl;

    // update balance
    balance += intrst;
}

int main()
{
    sav_account sav;
    sav.create("Saving");

    float d;
    cout << " Enter your deposit amount : ";
    cin >>d;

    sav.deposit(d);
    sav.display();

    int t;
    cout << "\n press '1' to see your interest : \n"
         << " press '0' to skip : ";
    cin >> t;
    if(t == 1)
        sav.interest();

    cout << "\n Enter your withdrawal amount : ";
    float w;
    cin >> w;
    sav.withdraw(w);
    sav.display();

    return 0;
}

8.2 An educational institution wishes to maintain a database of its employees. The database is divided into a number of classes whose hierarchical relationships are shown in the following figure. The figure also shows the minimum information required for each class. Specify all classes and define functions to create the database and retrieve individual information as and when required.

在这里插入图片描述

#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class staff
{
public:
    int code;
    char name[100];

public:
    void setInfo(char *n, int c)
    {
        strcpy(name, n);
        code = c;
    }
};

class teacher: public staff
{
private:
    char pub[100], sub[100];
public:
    void setDetail(char *s, char *p)
    {
        strcpy(sub, s);
        strcpy(pub, p);
    }
    void show()
    {
        cout<< "Name" << setw(8) << "Code" << setw(15)
            << "Subject" << setw(25) << "Publications" << endl
            << name << setw(8) << code << setw(25) << sub << setw(25) << pub << endl;
    }
};

class officer: public staff
{
    char grade[100];
public:
    void setDetail(char *g)
    {
        strcpy(grade, g);
    }
    void show()
    {
        cout<< "Name" << setw(15) << "Code" << setw(15)
            << "Category" << setw(10) << endl
            << name << setw(10) << code << setw(25) << grade << endl;
    }
};

class typist: public staff
{
protected:
    float speed;
public:
    void setSpeed(float s)
    {
        speed = s;
    }
};

class regular: public typist
{
private:
    float wage;
public:
    void setWage(float w) {wage = w;}
    void show()
    {
        cout<< "Name" << setw(16) << "Code" << setw(15)
            << "Speed" << setw(15) << "Wage" << endl
            << name << setw(10) << code << setw(15) << speed << setw(15) << wage << endl;
    }
};

class casual: public typist
{
private:
    float wage;
public:
    void setWage(float w) {wage = w;}
    void show()
    {
        cout<< "Name" << setw(16) << "Code" << setw(15)
            << "Speed" << setw(15) << "Wage" << endl
            << name << setw(10) << code << setw(15) << speed << setw(15) << wage << endl;
    }
};

int main ()
{
    teacher t;
    t.setInfo("Stefan", 420);
    t.setDetail("C++ Programming", "Effective C++");

    officer o;
    o.setInfo("Rimo", 222);
    o.setDetail("First Class");

    regular rt;
    rt.setInfo("Chris", 332);
    rt.setSpeed(85.5);
    rt.setWage(15000);

    casual ct;
    ct.setInfo("Richar", 129);
    ct.setSpeed(90);
    ct.setWage(21000);

    cout << " About Teacher : " << endl;
    t.show();

    cout << "About Officer : " << endl;
    o.show();

    cout << " About Regular Typist : " << endl;
    rt.show();

    cout << "About Casual Typist : " << endl;
    ct.show();

    return 0;
}
  • 17
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值