c++ 9、面向对象(类与对象)

2020-05-10  本文已影响0人  八戒无戒

1、类的定义
c++在c的基础上加入了面向对象的编程思维,类的定义如下:

class Object
{
public:
    double attribute1;
    double attribute2;
    void method1();
    void method2();
protected:
    string attribute3;
private:
    int attribute4;
};

其中public,protected,private为类成员修饰符,决定了类成员的访问属性。
attribute为类的属性,method为类的方法,attribute和method统称为类的成员。

2、类的实例(对象)及对象的访问
类的实例,即生成对象与声明变量一样。

int main()
{
        Object object1;
        Object object2;
        return 0;
}

成员的访问(通过成员访问运算符.),如下例:

#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;

class Rectangle
{
public:
    double length;         // 声明类属性
    double width;          // 声明类属性
    double getSquare();   // 声明类方法
};

// 定义类方法
double Rectangle::getSquare()        
{
    return length * width;
}

int main()
{
    Rectangle r;          // 实例对象
    r.length = 25.0;      // 访问类属性
    r.width = 25.0;       // 访问类属性
    double square;
    square = r.getSquare();      // 访问类方法
    cout << "面积等于:" << square << endl;
    return 0;
}

运行结果:

面积等于:625

3、类成员修饰符

  • public:公有成员,公有成员在程序中类的外部是可访问的,可以不使用任何成员函数来设置和获取公有变量的值
  • private: 私有成员,在类的外部是不可访问的,只有类成员方法和友元函数可以访问。
  • protected: 保护成员,与private相似,不同点在于被protected修饰的成员,其子类(派生类)是可以访问的
class Rectangle
{
public:
    double length;
    double getSquare();
private:
    double width;
};

int main()
{
    Rectangle r;
    r.length = 25.0;
    r.width = 25.0;             // 访问非法
    double square;
    square = r.getSquare();
    cout << "面积等于:" << square << endl;
    return 0;
}

上面例中width为类的私有成员,而在main()函数中直接访问编译是会报错的。
报错结果如下:
“Rectangle::width”: 无法访问 private 成员(在“Rectangle”类中声明)

上一篇下一篇

猜你喜欢

热点阅读