C ++, static const difference with

const keyword

const keyword you can modify variables, objects, functions, etc.

const aAfter a variable is added const are constants

const piont apoint is a class object

int x() constFunction

  • Const member variable objects are not allowed to be changed.
  • const object can only call const member functions, rather than a const object const member functions can access

for example:

#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;
}

operation result:

Because const object can only call const member functions, rather than a const object can access const member functions, b const object is a type object, but x () const member functions are not, it will be an error

Correct codes :

#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;
}

Operating results :

The static keyword

  • static member variables in a class belongs to the class owned, all objects of a class of only one copy.
  • static member functions in a class belongs to the class owned, this function does not receive this pointer, static member variables which can only access the class.

for example:

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

Guess you like

Origin www.cnblogs.com/liuchenxu123/p/12516956.html