C++関数の前後にconstを付ける違い

2795 ワード

1、関数前後const
関数前const:通常関数またはメンバー関数(非静的メンバー関数)の前にconst修飾を加えることができ、関数の戻り値がconstであることを示し、変更できません.書式:
const returnType functionName(param list)

関数後にconstを追加:クラスの非静的メンバー関数のみがconst修飾を追加できます.このクラスのthisポインタがconstタイプであり、クラスのメンバー変数の値を変更できないことを示します.すなわち、メンバー変数はread only(例外は2を参照)であり、メンバー変数を変更する行為はすべて非法です.このタイプの関数は、次の形式で読取り専用メンバー関数と呼ばれます.
returnType functionName(param list) const

説明:クラス内のconst(関数の後に追加)とstaticはメンバー関数を同時に修飾できません.理由は、次の2点です.1 C++コンパイラは、constのメンバー関数を実装する際に、クラスのインスタンス状態を変更できないように、関数に暗黙的なパラメータconst this*を追加します.しかし、メンバーがstaticの場合、この関数にはthisポインタがありません.つまり、constの使い方とstaticは衝突します.②両者の意味は矛盾している.staticの役割は、この関数がタイプの静的変数にのみ作用し、クラスのインスタンスとは関係がないことを示すことです.constの役割は、関数がクラスのインスタンスの状態を変更できず、タイプの静的変数とは関係がないため、同時に使用できないことを保証することです.
2、constとmutableの違い
文字通り、mutalbeは「可変、可変」であり、constant(C++のconst)とは反義語である.C++ではmutableもconstの制限を突破するために設定されています.mutableで修飾された変数(メンバー変数)は、const関数でも常に可変状態になります.したがって、ポストconstメンバー関数では、クラスのmutableタイプのメンバー変数を変更できます.
#include 
using namespace std;

class A{
private:
	int m_a;//int  mutable           
public:
	A():m_a(0){}
	int setA(int a) const
	{
		this->m_a = a;//error: l-value specifies const object
	}

	int setA(int a)
	{
		this->m_a = a;
	}
};

int main()
{
	A a1;
	
	return 0;
}

コンパイルエラー:error C 2166:l-value specifies const object、左値はconst、すなわちconst修飾後メンバー関数のthisポインタはconstであり、その指すメンバー変数は修正できず、メンバー変数をmutable修飾後にコンパイルする.
3、constメンバー関数とconstオブジェクト
constメンバー関数には、定数オブジェクト相関というもう一つの役割があります.組み込まれたデータ型では、定数を定義できます.ユーザーがカスタマイズしたクラスタイプでも、定数オブジェクトを定義できます.1、constオブジェクトは後constメンバー関数のみを呼び出すことができる.
#include 
using namespace std;

class A{
private:
	int m_a;
public:
	A():m_a(0){}
	int getA() const
	{
		return m_a;
	}
	int GetA() // const    ,      const       
	{
		return m_a;
	}
	int setA(int a)
	{
		this->m_a = a;
	}
};

int main()
{
	const A a2;//const  
	int t;
	t = a2.getA();
	t = a2.GetA();//error:const object call non-const member function,only non-const object can call


	return 0;
}

エラーは、error C 2662:‘GetA’:cannot convert‘this’pointer from‘const class A’to'class A&’②、非constオブジェクトはconstメンバー関数を呼び出すこともできるし、非constメンバー関数を呼び出すこともできる.
#include 
using namespace std;

class A{
private:
	int m_a;
public:
	A():m_a(0){}
	int getA() const
	{
		return m_a;
	}
	int GetA()
	{
		return m_a;
	}
	int setA(int a)
	{
		this->m_a = a;
	}
};

int main()
{
	A a1;// const  
	int t;
	t = a1.getA();//  const    ,  
	t = a1.GetA();//   const    ,  

	return 0;
}

リファレンス
https://www.iteblog.com/archives/214.html https://blog.csdn.net/qq_32739503/article/details/83341222 https://blog.csdn.net/bxyill/article/details/8444391