2017-01-21 3 views
-2

大学から、constメソッドはフィールドを変更できないと思いました。 私はC++に戻っています。私は簡単なプログラムを書いています。C++言語のconstメソッド

#include "stdafx.h" 

#include <iostream> 

using namespace std; 

class Box 
{ 
    int a; 
    int b; 
    int square; 

public: 
    Box(int a, int b) 
    { 
     this->a = a; 
     this->b = b; 
    } 
    const void showSquare(void) const 
    { 
     cout << this->a * this->b << endl; 
    } 

    const void setDim(int a, int b) 
    { 
     this->a = a; 
     this->b = b; 
    } 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    Box b(2, 4); 
    b.showSquare(); 
    b.setDim(2, 5); 
    b.showSquare(); 
    int a; 
    cin >> a; 
    return 0; 
} 

私の場合、constメソッドはクラスのフィールドを変更できますか? どうすれば可能ですか?

あなたより先です。

+4

const void setDim(int a、int b)は、constメソッドの適切なシグネチャではありません。それは 'void setDim(int a、int b)const'です。 –

+0

'showSquare()'は "フィールド"を変更しないことを示すために 'const'を使います。 'setDim()'は 'const'を使って関数の戻り値が変わらないことを示します(無意味ですが、' void'を返すときには許されます)が、関数が "fields"を変更するかどうかは関係ありません。 – Peter

答えて

1

setDimconstの方法ではありません。メソッドの戻り値の型はconst voidです。メソッドがvoidを返すので、constは実際には違いはありません。

あなたは方法がconst法(ないオブジェクトの状態を変更することになっ法)のように動作する場合、署名の最後にconstを移動

void setDim(int a, int b) const 
    { 
     // do read only operations on the object members. 
    } 

How many and which are the uses of “const” in C++?は次のようになります良いリフレッシャー。

0

constのボイドは、会員データを変更することはできません。このポインタのconstのconstではありません、戻り値である:

class A 
{ 
    public: 
     void show()const // this pointer here is constant so this method cannot change any member data or Call any other non-const member 
     { 
      a = 0; // compile time-error 

      setValue(7); // also compile time error: `error C2662: 'setValue' : cannot convert 'this' pointer from 'const class A' to 'class A &'` 
      cout << a << endl; 
     } 

     const void setValue(const int x) 
     { 
      a = x; // ok 
     } 

     private: 
      int a; 
}; 
0

説明いただきありがとうございます。今私はconstメソッドを理解しています。