细嚼慢咽C++primer(4)——类(1):构造函数,类型别名

1  最简单地说,类即使定义了一个新的类型和一个新的作用域。

2  基础

1  构造函数

构造函数一般应使用一个构造函数初始化列表,来初始化对象的数据成员。

Sales_item(): units_sold(0), revenue(0.0)  {};

2  成员函数

在类内部定义的函数默认为inline.

将关键字const加在形参表之后,就可以将成员函数声明为常量:

double avg_price() const;

const成员不能改变其所操作的对象的数据成员。const必须同时出现在声明和定义中,若只出现在其中一处,就会出现一个编译时错误。


习题12.1:

using namespace std;
class Person {
    private:
        string name;
        string address;
}


习题12.2:

using namespace std;
class Person {
    Persion(string &name, string &addr)
    {
    }
    private:
        string name;
        string address;
};

习题12.3:

using namespace std;
class Person {
    Persion(string &name, string &addr)
    {
    }
    private:
        string name;
        string address;
    public:
        string getName() const
        {
            return self.name;
        }
        string getAddr() const
        {
            return self.address;
        }
};
返回名字和地址的操作不应该修改成员变量的值,所以应该指定成员函数为const。


习题12.4:

name和address为private实现数据隐藏, 函数getName() 和getAddr()为public提供接口,构造函数通常也为public.


3  数据抽象和封装

在C++中,使用访问标号(public, private, protected)来定义类的抽象接口和实施封装。

两个优点:

  • 避免类内部出现无意的,可能破坏对象状态的用户级错误;
  • 随时间推移可以根据需求改变或缺陷报告来完善类实现,而无需改变用户级代码。

习题12.5:

C++支持三种访问标号,public private protected


习题12.6:

class关键字定义的类,默认的访问权限为private,struct关键字定义的类,默认的访问权限是public。


习题12.7:

封装是一种将低层次的元素组合起来形成新的,高层次实体的技术。

封装隐藏了内部元素的实现细节。


4 使用类型别名来简化类

类可以定义自己的局部类型的名字。

class Screen {
public:
    // interface member functions
    typedef std::string::size_type index;
private:
    std::string contents;
    index cursor;
    index height, width;
};

可以在类定义体内指定一个成员为inline,作为其声明的一部分,或者,也可以在类定义体外部的函数定义上指定inline。在声明和定义处指定inline都是合法的。

注意:inline成员函数的定义必须在调用该函数的每个源文件中是可见的,不在类体内定义的inline成员函数,其定义通常应放在有类定义的同一头文件中。


12.8:

class Sales_item {
    public:
        double avg_price() const;
        bool same_isbn(const Sales_item &rhs) const
        {
            return isbn == rhs.isbn;
        }
    private:
        std:string isbn;
        unsigned units_sold;
        double revenue;
};
inline double Sales_item :: avg_price() const
{
    if (units_sold) 
        return revenue/units_sold;
    else
        return 0;
}

其他的两种写法:

  • 将成员函数的定义写在类内部;
  • 在类内部进行成员函数的声明时,指定inline关键字。

习题12.9:

class Screen {
public:
    // interface member functions
    typedef std::string::size_type index;
    Screen(index ht, index wt, const std::string &cntnts)
    {
        height = ht;
        width = wt;
        contents = cntnts;
    }
private:
    std::string contents;
    index cursor;
    index height, width;
};





posted @ 2013-09-29 19:50  suzhou  阅读(248)  评论(0编辑  收藏  举报