静态函数中的静态变量
Static variable inside a static function?
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 的类定义中?
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板基类中的静态变量
- 类和静态变量
- 不同作用域中的静态变量和全局变量
- 静态变量声明和定义
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 在类中继承静态变量?
- "local scope"中的 C++ 初始化静态变量
- 使用静态变量的递归调用的不同输出
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 复制文件流C++静态变量
- 如何在复杂继承中访问静态成员变量
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 跨模板化函数编译的静态变量
- constexpr函数中的静态constexpr变量
- 静态成员变量不会由 gettext 转换
- 从 exe 和 dll 访问静态库中的 extern 变量
- 如果包含映射的静态库与可执行文件和动态库链接,静态映射(变量)是否会被多次释放?
- 用于定义公共变量静态常量整数的C++标准