c++ - C++类中的静态动态二维数组

标签 c++ arrays class

我想做这样的事情:

Class myclass
{
private:
static int **board;
public:
myclass();
};

然后在cpp文件中

board = new int*[x];
for (int i = 0; i < x; i++) {
    board[i] = new int[y];
}

我的目标是只有一个board,无论我制作了多少对象。

最佳答案

你正在寻找Singleton,链接在这里是关于这个的维基百科页面

https://en.wikipedia.org/wiki/Singleton_pattern

Singleton 的一个非常简单的实现是:

static int ** getBoard() {
    if (!board) {
        board = new int*[x];
        for (int i = 0; i < x; i++) {
            board[i] = new int[y];
        }
    }
    else {
        return board;
    }
}

并且您可以使用myclass::getBoard() 来获取板。

根据您的要求,您可能需要一些变体。

关于c++ - C++类中的静态动态二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46311073/

相关文章:

javascript - 将元素从一个对象添加/合并到数组内的另一个对象

python - 什么是数据类,它们与普通类有何不同?

php - 使用 php 类进行用户身份验证。这是正确的吗?

C++ 将模板参数包从一个可变参数模板传递到另一个模板会导致编译器错误

c++ - 在x64模式下从C++/CLI调用MASM PROC会产生意外的性能问题

c++ - 从给定字符串中查找长度为 k 的所有排列/组合

具有静态类成员的 C++ 模板类

c++ - 返回 STL 容器元素的引用

C++ - 生成子类实例的父类(super class)构造函数

php - 遍历 JSON 数组