C++迈向精通:学习笔记:类属性与类方法

类属性与类方法

注意:这不是教程,是学习笔记,不适合初学者阅读!!

类属性与方法

成员属性与成员方法

在类中定义的方法与属性,就叫做成员属性与方法。

类属性与类方法

依然在类里面,但区别是:

  • 属性:A有自己的成员属性,B有自己的成员属性,C也有自己的成员属性。也就是它们的成员属性都是不一样的,每一个人都拥有属于自己的成员属性。而类属性则是指的每个成员所访问的属性空间是一样的,大家拥有的是同一份。
  • 方法:在成员方法中,我们可以访问 this 指针,如果在类方法中,不可以访问 this 指针。

访问类属性的三个方法:

  • 通过对象访问
  • 通过类的命名空间
  • 通过作用域的默认规则
class Point {
public :
    Point() : x(0), y(0) {}
    Point(int x, int y) : x(x), y(y) {}
    void set_x(int x) { this->x = x; }
    void set_y(int y) { this->y = y; }
    int get_x() {
        // this->get_x_cnt++;
        // get_x_cnt++;
        Point::get_x_cnt++; // 每次调用get_x,get_x_cnt加1
        return this->x; 
    }
    int get_y() { return this->y; }

private :
    // 定义类属性
    // 现在来实现这样的一个需求:get_x被调用的次数
    // static的作用是使得该变量不需要依赖对象来访问
    static int get_x_cnt; // 声明类属性
    int x, y;
}

最不容易让人出错的方式:通过命名空间访问 Point::get_x_cnt++

类的作用域:

成员变量只在类中有效。

代码示例,演示了类属性、类方法和作用域:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <list>
#include <queue>
#include <stack>
#include <deque>
#include <bitset>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <ctime>
#include <cassert>
#include <complex>
#include <numeric>
#include <algorithm>
#include <iomanip>
#include <climits>
#include <limits>
#include <chrono>

using namespace std;

class Point {
public :
    Point() : x(0), y(0) {}
    Point(int x, int y) : x(x), y(y) {}
    void set_x(int x) { this->x = x; }
    void set_y(int y) { this->y = y; }
    int get_x() {
        // this->get_x_cnt++;
        // get_x_cnt++;
        Point::get_x_cnt++; // 每次调用get_x,get_x_cnt加1
        return this->x; 
    }
    int get_y() { return this->y; }

    // 类方法:
    static int x_cnt() {
        return Point::get_x_cnt; // 返回类属性
    }

private :
    // 定义类属性
    // 现在来实现这样的一个需求:get_x被调用的次数
    // static的作用是使得该变量不需要依赖对象来访问
    static int get_x_cnt; // 声明类属性
    int x, y;
};

int Point::get_x_cnt = 0; // 初始化类属性,定义

int main() {
    Point p1(3, 4), p2(5, 6);
    cout << p1.get_x() << "," << p1.get_y() << endl;
    cout << p2.get_x() << "," << p2.get_y() << endl;
    p1.get_x(), p1.get_x(), p1.get_x();
    cout << "x_cnt :" << Point::x_cnt() << endl;
    return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若亦_Royi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值