您的位置:首页 > 其它

12.1类的定义和声明

2016-10-17 20:58 148 查看
1.类成员

类就是定义了一个新的类型和一个新的作用域。每个类都可能会定义一个或几个特殊的成员函数来告诉我们如何初始化类类型的变量。

一个类可以包含public、private、protected三部分。 public部分定义的成员可使用该类型的所有代码访问;private 部分定义的成员可被其他类成员访问。

2.构造函数

定义如何进行初始化的成员函数称为构造函数(constructor)。和其他函数一样,构造函数能接受多个参数。构造函数是一个特殊的、与类同名的成员函数,

用于给每个数据成员设置适当的初始值。

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

Sales_item(string &book,unsigned units,double amount)
:isbn(book),units_sold(units),revenue(amount)//构造函数初始化列表由成员名和带括号的初始值组成,跟在形参表后,以:开头
3.成员函数

<span style="font-size:12px;">#include <iostream>
#include<string>

using namespace std;

class Person//整个类叫封装
{
public://类的接口
Person(const std::string &nm,const std::string &addr):name(nm),address(addr)//初始化列表
{
//name=nm;
//address=addr;

}
std::string getName() const
{
return name;
}
std:: string getAddress() const//只读数据
{
return address;
}
private:// 定义类内部的数据,并将数据隐藏
std::string name;
std::string address;

};
int main()
{
Person a("张飞","花园街5号");
cout<<a.getName()<<","<<a.getAddress()<<endl;

return 0;
}</span>
成员函数有一个附加的隐含实参,将函数绑定到调用函数的对象:a.getName()就是在调用名为a的对象的getName函数。 将const 加在形参表之后,就

可以将函数声明变为常量。注意:const 必须同时出现在声明和定义中。

12.1.2 数据抽象和封装

数据抽象是一种依赖于接口和现实 分离的编程技术。封装是一项将低层次的元素组合起来形成新的、高层次实体的技术。类是一个封装的实体:它代表若干

成员的聚集。

12.1.3more 类定义

1.同一类型的多个数据成员

2.使用类型 别名来简化类

3.成员函数可被重载:两个重载成员的形参数量和类型不能相同。

4.显式指定inline成员函数

/* 同一类型的多个数据成员
使用类型别名来简化类
成员函数可被重载-
显法指定inline成员函数
*/
#include <iostream>
#include<string>

using namespace std;

class Screen
{
public:
typedef std::string::size_type index;//使用类型的别名来简化代码
Screen(index ht=0,index wd=0):contents(ht*wd,'A'),cursor(0),height(ht),width(wd)
{}

char get() const; //函数的声明

char get(std::string ::size_type r,std::string ::size_type c) const
{
std::string ::size_type row=r*width;
return contents[row+c];

}

private:
std::string contents;
std::string ::size_type cursor;
std::string ::size_type height,width;

};
<pre name="code" class="cpp" style="font-size: 13.3333px;">inline char Screen::get() const//inline 内联函数,函数的定义
{
return contents[cursor];
}
int main(){Screen a(10,100);cout<<a.get()<<endl;cout<<a.get(2,8)<<endl;cout<<"测试"<<endl;return 0;}


12.1.4 类声明和类定义

class Screen ;//声明一个类

这个声明,称为前向声明(forward declaration),在声明之后,定义之前,类Screen是一个不完全类型(incompete type),不完全类型只能用于定义指向该类型的指针及引用,或者用于声明(不是定义)使用该类型作为形参类或返回类型的函数。

类声明:1.类完全定义,数据成员才能指定为该类类型.2.不完全类型,数据成员只能指向该类型的指针或引用。

class LinkScreen{
Screen window;
LinkScreen *next;
LinkScreen *prev;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  类定义 类声明