[英]Static variable inside a static function?
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
static void displayPool() {
MyString::table->displayAllStrings();
}
這不是你認為它正在做的事情。 它定義了自由功能displayPool
。 關鍵字static
所做的全部工作就是將函數保留在定義函數的源文件本地。 您想要定義靜態成員函數MyString::displayPool()
:
void MyString::displayPool() {
table->displayAllStrings();
}
displayPool
之前的MyString::
是必不可少的。 您不希望在此處使用static
關鍵字; 添加那將是一個錯誤。 最后,請注意,不需要MyString::
來限定table
。 靜態成員函數無需限定即可查看所有靜態數據成員。 您需要限定table
的唯一原因是是否存在一個名為table
的全局變量。 那么table
將是模棱兩可的。
在這種情況下,您需要以下內容:
void MyString::displayPool() {
MyString::table->displayAllStrings();
}
如果要在靜態函數中使用靜態變量,則應該執行以下操作:
static void displayPool() {
static StringTable* table = new StringTable();
table->displayAllStrings();
}
但是我有一個問題可能是要求您為某個類創建一個靜態方法。 您可能想重新閱讀該問題。
你宣布了嗎
StringTable* table;
在具有公共訪問說明符的MyString的類定義中?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.