luqingfei@C++

为中华之崛起而崛起!
兼听则明,偏听则暗。

关于C++中类的基础练习

本次练习的内容,涉及到C++中类的构造函数,默认构造函数,副本构造函数,构造函数中的成员初始化列表,类的数据成员,类的成员函数,友元函数,等技术点。

下面有4道题:
1、创建一个简单的类Integer,它只有一个私有数据成员int。为这个类提供构造函数,并使用它们输出创建对象的消息。提供类的成员函数,获取和设置数据成员,并输出该值。编写一个测试程序,创建和操作几个Integer对象。在测试程序中获取,设置和输出每个对象的数据成员值,以验证这些函数。
2、修改上一题类Integer的构造函数,把数据成员初始化为初始化列表中的0,并实现类的副本构造函数。编写一个成员函数,比较当前对象和作为参数传送的Interger对象。如果当前对象小于参数,该函数就返回-1,如果它们相等,函数就返回0,如果当前对象大于参数,函数就返回+1。测试该函数的两个版本:第一个版本的参数按值传送,第二个版本的参数按引用传送。在调用函数时,构造函数会输出什么结果?解释出现这种结果的原因。类中的函数不能是重载函数,为什么?
3、为类Integer实现成员函数add()、subtract()和multiply(),对当前对象和Integer类型的参数值进行加、减和乘法运算。在类中用main()演示这些函数的操作,main()创建几个Integer对象,它们分别包含值4、5、6、7和8,再使用这些对象计算4*5*5*5+6*5*5+7*5+8的值。实现这些函数,使计算和结果的输出在一个语句中完成。
4、修改题2的解决方法,把compare() 函数实现为类Integer的一个友元。

参考答案:

Integer.h

integer.cpp

// main.cpp
#include <iostream>
#include 
"integer.h"
using std::cout;
using std::endl;

void main() {
    Integer integer;
    cout 
<< "Default value of integer: " << integer.getValue() << endl;

    integer.setValue(
100);
    cout 
<< "Value of integer: " << integer.getValue() << endl;

    Integer int2(integer);
    cout 
<< "Copy obj: " << int2.getValue() << endl;

    Integer int3(
999);
    cout 
<< int3.getValue() << endl;

    
int result = int2.compare(int3);
    cout 
<< result << endl;

    result 
= compare(int2, int3);
    cout 
<< result << endl;


    
// 4*5*5*5 + 6*5*5 + 7*5 + 8
    Integer int4(4);
    Integer int5(
5);
    Integer int6(
6);
    Integer int7(
7);
    Integer int8(
8);

    Integer
* result2 = int4.multiply(int5)->multiply(int5)->multiply(int5)->
        add(int6.multiply(int5)
->multiply(int5)->getValue())->
        add(int7.multiply(int5)
->getValue())->add(int8);

    cout 
<< "4*5*5*5 + 6*5*5 + 7*5 + 8 = " << result2->getValue() << endl;

}

int compare(const Integer& ineger1, const Integer& integer2){
    cout 
<< "friend function:" << endl;

    
if (ineger1.value<integer2.value) 
        
return -1;
    
else if (ineger1.value==integer2.value) 
        
return 0;
    
return 1;
}

posted on 2009-02-27 18:10 luqingfei 阅读(826) 评论(0)  编辑 收藏 引用 所属分类: C++基础


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2009年2月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
1234567

统计

留言簿(6)

随笔分类(109)

随笔档案(105)

Blogers

Game

Life

NodeJs

Python

Useful Webs

大牛

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜