C++类

C++中的类用于模拟现实中的事物,包含类属性和方法。

1.类声明

类声明由 class 关键字 组成,加上花括号的类体,与及;作为结尾

#include <iostream>
using namespace std;
class Range {
public:
    int width;
    int height;
    int getRange() {
        return width *height;
    };
    Range(int w, int h):width(w), height(h){};
    Range(){};
};

通常情况下,类声明放在头文件里面,而把方法的定义,如getRange放在cpp源文件当中


2.构造函数

构造函数与类名相同,并且不含返回值。如

int Range(int w, int h):width(w), height(h) {};

(1).构造函数由类型和初始值语句组成,

(2).构造函数可以写在类声明外面,如:
int Range::Range():width(0), height(0) {};
其中::表示来自哪个类,或者说是哪个命名空间下
(3)构造函数参数类型可以是字符变量,指针,引用

3.成员函数

成员函数访问区域:

(1).当前类的所有属性和方法
(2).继承类中的protected, public属性和方法
(3).访问友元类的的属性和方法

成员函数隐式包含this指针,默认调用类的属性或者方法时,无需要带前缀this.

如:

    int getRange() {
        return width *height;
    };

4.类对象

新建类对象的方式:

class Range{
    //......
}range1, range2;

Range r2;
Range r3();
Range r4(9, 8);
Range *r5 = new Range();
Range *r6 = new Range(3, 4);

 

6.类继承

class Circle:puclic Range{

};

public, protected, private继承区别

public: 子类能访问基类的public 和 protected属性和方法

protected: 子类能访问public 和 protected属性和方法,继承过来的public变成protected权限

private: 继承下来的public 和 protected属性和方法变成private权限,基础子类再继承下去的类将不再具有父类的属性和方法的访问权限



原文地址:https://www.cnblogs.com/haiyupeter/p/2660039.html