封装
所有的 C++ 程序都有以下两个基本要素:
函数:这是程序中执行动作的部分,它们被称为函数或方法。
数据:数据是程序的信息,会受到程序函数的影响,也叫属性。
封装是面向对象编程中的把数据和操作数据的函数绑定在一起的一个概念,这样能避免受到外界的干扰和误用,从而确保了安全。
我们已经知道,类包含私有成员(private)、保护成员(protected)和公有成员(public)成员。默认情况下,所有的数据成员和函数成员都是私有的。
为了使类中的成员变成公有的(即程序中的类外部的其他部分也能访问),必须在这些成员前使用 public 关键字进行声明。所有定义在 public 标识符后边的属性或函数可以被程序中所有其他的函数访问。
例子:
#include <iostream>
using namespace std;
class Adder{
public:
// 构造函数
Adder(int i = 0)
{
total = i;
}
// 对外的接口
void addNum(int number)
{
total += number;
}
// 对外的接口
int getTotal()
{
return total;
};
private:
// 对外隐藏的数据
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total is " << a.getTotal() << endl;
return 0;
}
运行结果:
Total is 60
上面的类把数字相加,并返回总和。公有成员 addNum 和 getTotal 是对外的接口,用户需要知道它们以便使用类。私有成员 total 是对外隐藏的(即被封装起来),用户不需要了解它,但它又是类能正常工作所必需的。
类的设计策略:
通常而言,要把类的数据成员设计成私有(private),类的函数成员则根据实际需要设计成publice, protected或private。
继承
#include <iostream>
using namespace std;
class Animal
{
protected:
float weight;
public:
void setWeight(float w)
{
weight = w;
}
float getWeight()
{
return weight;
}
void breathe()
{
cout << "breathing..." << endl;
}
};
class Dog : public Animal
{
private:
int legs;
public:
void setLegs(int number)
{
legs = number;
}
int getLegs()
{
return legs;
}
void bark()
{
cout << "wang! wang!" << endl;
}
};
int main(int argc, char** argv)
{
Dog dog;
dog.setWeight(12.5);
dog.setLegs(4);
cout << "The dog's weight is " << dog.getWeight() << "kg" << endl;
cout << "The dog has " << dog.getLegs() << " legs" << endl;
dog.breathe();
dog.bark();
return 0;
}
运行结果:
The dog’s weight is 12.5kg
The dog has 4 legs
breathing...
wang! wang!
程序分析:
(1)Animal为一个类,Dog为另一个类。
class Dog : public Animal 表示Dog类继承了 Animal类。此时,Animal就成了Dog的基类或父类。Dog就成了Animal的派生类或子类。
(2)体重和呼吸是所有动物的共性,所以weight和breathe()定义在类Animal中。腿和吠不是所有动物的共性,所以legs和bark()定义在了类Dog中。
(3)class Dog : public Animal , 这里的public表示继承方式 。
继承方式有三种:public, protected和private。
① 父类为private的属性和方法,不能被子类继承。
② 父类为protected的成员,若被子类public继承的,仍为子类的protected成员;若被子类protected或private继承的,变为子类的private成员。
③ 父类为public的成员,若被子类public继承的,仍为子类的public成员;若被子类protected继承的,变为子类的protected成员;若被子类private继承的,变为子类的private成员。
(4)根据(3)中第③条的结论,若程序改为class Dog : protected Animal,则程序无法通过编译。因为setWeight()和getWeight()被protected继承后,变为Dog的protected成员,而protected成员,无法在类外部(比如main函数中)访问。
网友评论