2012-02-10 3 views
1

私はclass Stringです。これはcharactersという動的配列を持ちますが、初期化後は変更できません。だから私はそれを初期化し、引き続き引数の変更を防ぐ必要があります。クラスを初期化して引数の値をフリーズする方法

どうすればいいですか? :)

+1

ワイズ・ロバは不変クラスのこの種が呼び出され – guitarflow

+1

「不変」、これらのクラスを呼び出す「不変」 –

答えて

4

メンバーをconstにする。そしてコンストラクタで初期化を行います。

class String 
{ 
    const char* const _buff; //both the contents and the pointer are const 
public: 
    String (const char* buff); 
}; 

String::String(const char* buff) : _buff(buff) 
{ 
} 

EDIT:@ildjarnが指摘しているように、不変オブジェクトを使用する場合は特に注意してください。あなたはそれがあなたが実際に必要としているものであることが確実でなければなりません。標準的なコンテナでそれらを使用することも、論理的なコピーを持つこともできません。

+1

作るデータメンバのconstがちょうど愚かである - それはあなたのクラスは、非作りますC++ 03標準コンテナでクラスのインスタンスを使用できないことを意味するassignableです。 sanerの解決策は、前記データメンバにアクセスし、データメンバ自身を非constのままにするconstメンバ関数を提供することである。 – ildjarn

+0

ありがとうございますが、このクラスのコピーコンストラクタを作成するにはどうすればよいですか?デストラクタ? :) – Vidak

+0

@Vidakメンバーを同じままにしたいのですか? –

1

innerstringの配列をprivate constとして設定し、getメソッドのみを公開します。

0

ホープ、このことができます:

#include <iostream> 
#include <cstring> 
#include <vector> 

class String { 
public: 

    // Default constructor and 
    // conversion constructor 
    String(const char *p = "") { 
    data_ = new char[strlen(p)+1]; 
    strcpy(data_, p); 
    } 


    // copy constructor 
    String(const String& rhs) { 
    data_ = new char[strlen(rhs.data_)+1]; 
    strcpy(data_, rhs.data_); 
    } 

    ~String() { 
    delete[] data_; 
    } 

    String& operator=(const String&rhs) { 
    String temp(rhs); 
    std::swap(temp.data_, data_); 
    return *this; 
    } 

    // operator[] is the only data access, and it returns "const&" 
    const char&operator[](std::size_t i) { return data_[i]; } 

private: 
    char *data_; 
}; 



int main() { 
    String a("Hello"); 
    String b("Goodbye"); 
    std::vector<String> v; 

    v.push_back("a"); 
    v.push_back("b"); 
    v.push_back(&b[4]); 

    b = a; 

    std::cout << &b[0] << "\n"; 
    std::cout << &v[2][0] << "\n"; 
} 
関連する問題