c++入门编程学习记录7

    科技2024-03-29  79

    20.10.7,学习c++的第七天

    学习内容

    类与对象

    封装

    class Circle { //访问权限,公共权限 public: //属性 int m_r; //行为 double calculateZC(){ return 2 * PI * m_r; } };

    访问权限有三种: 公共权限 public 类内可以访问 类外可以访问 保护权限 protected 类内可以访问 类外不可以访问 子类可以访问父类 私有权限 private 类内可以访问 类外不可以访问 子类不可以访问父类

    在C++中 struct和class唯一的区别就在于 默认的访问权限不同 。 (struct 默认权限为公共,class为私有)

    成员属性可设为私有:优点: 将所有成员属性设置为私有,可以自己控制读写权限;对于写权限,我们可以检测数据的有效性。

    对象的分文件

    一个定义在主文件的类如下所示:

    class point { private: int m_X; int m_Y; public: void setX(int x){ m_X = x; } int getX(int x){ return m_X; } void setY(int x){ m_Y = x; } int getY(int x){ return m_Y; } };

    下面将类写入分文件,主文件直接调用即可,类的定义不在主文件中。 首先建立一个point.h文件,其内容只包括成员(属性、行为)的声明。

    # pragma once # 防止头文件重复包含 #include<iostream> using namespace std; class Point { private: int m_X; int m_Y; public: void setX(int x); int getX(int x); void setY(int x); int getY(int x); };

    然后建立一个point.cpp文件,其中只包括对象的行为的定义。但是需要指明对象的名称。

    #include"point.h" void Point::setX(int x) { m_X = x; } int Point::getX(int x) { return m_X; } void Point::setY(int x) { m_Y = x; } int Point::getY(int x) { return m_Y; }

    最后,只需在主文件中包含相应h文件即可。

    #include<iostream> using namespace std; #include“point.h” int main() { return 0; }
    Processed: 0.016, SQL: 8