C++中static与const区别

const关键字

const关键字可以修饰变量、对象、函数等

const a a是变量 加const后是常量

const piont a point是类 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;
}

运行结果:

C++中static与const区别

因为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;
}

运行结果:
C++中static与const区别

static关键字

  • 在类中的static成员变量属于整个类所拥有,对类的所有对象只有一份拷贝。
  • 在类中的static成员函数属于整个类所拥有,这个函数不接收this指针,因而只能访问类的static成员变量。

举例说明:

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

原文链接: https://www.cnblogs.com/liuchenxu123/p/12516956.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++中static与const区别

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/336039

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午10:25
下一篇 2023年3月1日 下午10:26

相关推荐