静态函数中的静态变量

Static variable inside a static function?

本文关键字:变量 静态 静态函数      更新时间:2023-10-16

Java 字符串文字池的简单C++模拟

你好

我无法从 MyString 类中的私有静态变量进行调用。 知道吗?

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

这两者都是在 MyString 类中声明的。 table 是一个私有变量。

谢谢。

编辑:头文件

#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 的类定义中?