C++類中const一些用法

在類中的const基本有三種用法

const int func(); // 返回值是const類型

int func(const int); // 參數爲const類型

int func(int )const; // 爲const類型的成員函數,只能調用類中const類型的變量;

另外,當類的實例是const類型時,也只能調用類中的const成員函數,且只有類的成員函數才能被修飾爲const類型;

//Point.h
#include <iostream>
using namespace std;

class Point{
private:
    int x,y;

public:
    Point(int a,int b){
        x=a;y=b;
        cout<<"Point constructor is called !\n";
    };
    ~Point(){
    cout<<"Point destructor is called !\n";
    }
    
public:
    const int getX(){
        return x;
    }
    const int getY(){
        return y;
    }

public:
    void setX(const int a,int b) {
        x=a;y=b;
    }

public:
    void printPoint() const{
        cout<<"const type\n";
        cout<<"x="<<x<<",y="<<y<<endl;
    }
    void printPoint(){
        cout<<"non const type\n";
        cout<<"x="<<x<<",y="<<y<<endl;
    }
};
//main.cpp
#include <iostream>
#include "Point.h"
int main(int argc, const char * argv[])
{

    // insert code here...
    Point p(10,20);
    Point const p1(30,40);
    p1.printPoint();
    p.printPoint();
    //std::cout << "Hello, World!\n";
    return 0;
}

cout:

Point constructor is called !

Point constructor is called !

const type

x=30,y=40

not const type

x=10,y=20

Point destructor is called !

Point destructor is called !

Program ended with exit code: 0


將類中的

 void printPoint()

函數刪除時則輸出:

Point constructor is called !

Point constructor is called !

const type

x=30,y=40

const type

x=10,y=20

Point destructor is called !

Point destructor is called !

Program ended with exit code: 0


所以類中的非 const成員函數也可調用const類型成員函數。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章