2

Java文字列リテラルプールの単純なC++シミュレーション

やあ、

MyStringクラスのプライベート静的変数から呼び出しを行うことができません。何か案が?

static void displayPool() {
    MyString::table->displayAllStrings();
}
StringTable* (MyString::table) = new StringTable();

これらは両方ともMyStringクラスで宣言されています。テーブルはプライベート変数です。

ありがとう。

編集:ヘッダーファイル

#ifndef MYSTRING_H
#define MYSTRING_H

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
#define POOLSIZE 100

class StringTable {
 public:
    StringTable();
    int addString(const char *str);
    char* getString(int i);
    void deleteString(int i);
    void displayAllStrings();
    void addCount(int);
    void minusCount(int);
 private:
    char** array; //da pool
    int* count;
    int size;
    int numStrings;
};

class MyString {
 public:
   MyString(const char*);
   MyString(const MyString&);
   ~MyString();
   static void displayPool();
   MyString& operator=(const MyString &);
   char* intern() const;
 private:
   int length;
   int index;
   static StringTable* table;
   friend MyString operator+(const MyString& lhs, const MyString& rhs);
   friend ostream& operator<<(ostream & os, const MyString & str);
 }; 

#endif
4

4 に答える 4

6
static void displayPool() {
    MyString::table->displayAllStrings();
}

これは、あなたが思っていることをしていません。これは、自由関数を定義していますdisplayPool。キーワードstaticが行うことは、関数が定義されているソースファイルに対して関数をローカルに保つことだけです。必要なのは、静的メンバー関数を定義することですMyString::displayPool()

void MyString::displayPool() {
    table->displayAllStrings();
}

MyString::displayPool不可欠です。staticここではキーワードは必要ありません。それを追加するとエラーになります。MyString::最後に、資格を得る必要はないことに注意してくださいtable。静的メンバー関数は、資格を必要とせずにすべての静的データメンバーを表示できます。資格を得る必要がある唯一の理由は、 ;tableという名前のグローバル変数があった場合です。tableその後、tableあいまいになります。

于 2012-10-04T23:51:27.493 に答える
1

この場合に必要なのは次のとおりです。

void MyString::displayPool() {
    MyString::table->displayAllStrings();
}
于 2012-10-04T23:44:15.847 に答える
0

静的関数内に静的変数が必要な場合は、次のようにする必要があります。

static void displayPool() {
    static StringTable* table = new StringTable();

    table->displayAllStrings();
}

ただし、問題は、あるクラスの静的メソッドを作成するように求められている可能性があると感じています。問題を読み直したい場合があります。

于 2012-10-04T23:30:16.197 に答える
0

宣言しましたか

StringTable* table;

パブリックアクセス指定子を使用したMyStringのクラス定義で?

于 2012-10-04T23:34:32.850 に答える