C ++、と静的定数差

constキーワード

constがあなたは、変数、オブジェクト、関数、など変更することができますキーワード

const a変数が追加された後のconstは定数であります

const piont aポイントは、クラスオブジェクトであります

int x() const機能

  • constメンバ変数オブジェクトは変更することが許可されていません。
  • constオブジェクトにのみアクセスをすることができますconstメンバ関数ではなく、constオブジェクトののconstメンバ関数を呼び出すことができます

例えば:

#include <iostream>
using namespace std;

class Point{
public :
    Point(int x,int y);
    int x();
    int y();
    ~Point();
private :
    int __x,__y;

};

Point::Point(int x,int y):__x(x),__y(y){}
Point::~Point(){}

int Point::x(){
    return this->__x;
}
int Point::y(){
    return this->__y;
}

int main() {
    Point a(2,3);
    const Point b(3,4); //const 对象
    cout << a.x() << " " << a.y() << endl;
    cout << b.x() << " " << b.y() << endl;
    return 0;
}

結果:

constオブジェクトのみconstメンバ関数を呼び出すことができなくconstオブジェクトはconstメンバ関数にアクセスすることができるので、BのCONSTオブジェクトが型オブジェクトであるが、X()constメンバ関数ではない、それは誤りであろう

正しいコード

#include <iostream>
using namespace std;

class Point{
public :
    Point(int x,int y);
    int x() const;
    int y() const;
    ~Point();
private :
    int __x,__y;

};

Point::Point(int x,int y):__x(x),__y(y){}
Point::~Point(){}

int Point::x() const{
    return this->__x;
}
int Point::y() const{
    return this->__y;
}

int main() {
    Point a(2,3);
    const Point b(3,4);
    cout << a.x() << " " << a.y() << endl;
    cout << b.x() << " " << b.y() << endl;
    return 0;
}

業績

staticキーワード

  • クラスの静的メンバ変数は、一つのコピーのみのクラスのクラスが所有する、すべてのオブジェクトに属します。
  • クラスの静的メンバ関数を所有しているクラスに属し、この関数はクラスのみにアクセスすることができ、このポインタ、静的メンバ変数を受け取りません。

例えば:

https://blog.csdn.net/qq_43799957/article/details/104685863

おすすめ

転載: www.cnblogs.com/liuchenxu123/p/12516956.html