简介
C++中的面向对象和Java差不多,也有封装、继承、多态的特性,不过有几个自身的特殊的点,下文将一一归纳。
类&对象
创建一个类的大致结构:
例子:
#include <iostream>
using namespace std;
class Test
{
private:
/* data */
int a = 0;
int b = 10;
public:
static int staticNum;
Test(/* args */); //1
~Test();
void setA(int num);
int getA()
{
return a;
};
friend void getB(Test test); //3
};
Test::Test(/* args */) //1
{
cout << "create" << endl;
}
Test::~Test() //2
{
cout << "destory" << endl;
}
void Test::setA(int num)
{
a = num;
}
void getB(Test test) //3
{
cout << "test.b:" << test.b << endl;
}
int main()
{
Test test;
test.setA(10);
cout << test.getA() << endl;
getB(test);
return 0;
}
注意的点:
- 成员函数的实现可以写在class外面,和声明分开
- 析构函数(类名前面加个~),它会在每次删除所创建的对象时执行,有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
- 友元函数,定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。
继承
C++和Java不一样,是支持多继承的,而Java只能单继承,语法如下:
class <派生类名>:<继承方式1><基类名1>,<继承方式2><基类名2>,…
{
<派生类类体>
};
例:
#include <iostream>
using namespace std;
// 基类 Shape
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 基类 PaintCost
class PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
};
// 派生类
class Rectangle : public Shape, public PaintCost //1
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// 输出对象的面积
cout << "Total area: " << Rect.getArea() << endl;
// 输出总花费
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
关键点:
- 继承可以多继承,逗号分割,继承时可以选择继承方式,public、protected 或 private 其中的一个来修饰每个基类。它们的区别如下:
- 公有继承(public): 当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问。
- 保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员。
- 私有继承(private): 当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员。
这么看Java都是公有继承。
- 基类的构造函数、析构函数和拷贝构造函数不能被继承,另外友元函数也不能被继承,因为友元函数不是成员函数。
总结
总体来说,C++的继承很多地方和Java还是很像的,还有文章没记录到的函数重载,用virtual虚函数实现多态,数据封装概念,有Java的基础还是很容易理解这些概念的。