const修飾クラスメンバー関数
1、クラスでconstで修飾されたメンバー関数には、その関数でクラスデータメンバーの値を変更できないという役割があります.
2、const修飾のクラスオブジェクトについては、const修飾のメンバー関数のみを呼び出すことができ、const以外のメンバー関数を呼び出すことはできません.
一方、const修飾以外のクラスオブジェクトではpublicメンバー関数を呼び出すことができます.constの有無のリロードメンバー関数のペアである場合、非constクラスオブジェクトは非constメンバー関数を呼び出します.
class Test
{
public:
void fun(int x) const
{
x = 2;
a = 3; //error
b = 4; //error
}
private:
int a;
int b;
};
2、const修飾のクラスオブジェクトについては、const修飾のメンバー関数のみを呼び出すことができ、const以外のメンバー関数を呼び出すことはできません.
#include <iostream>
using namespace std;
class Test
{
public:
void fun(int x) const
{
x = 2;
}
void fun2()
{
}
private:
int a;
int b;
};
int main()
{
const Test t;
t.fun(1);
t.fun2(); //error
return 0;
}
一方、const修飾以外のクラスオブジェクトではpublicメンバー関数を呼び出すことができます.constの有無のリロードメンバー関数のペアである場合、非constクラスオブジェクトは非constメンバー関数を呼び出します.