【问题标题】:How to give a size to a square matrix in a class如何为类中的方阵指定大小
【发布时间】:2013-05-26 11:09:36
【问题描述】:

我需要给类内的矩阵一个大小,但是编译器会抱怨const int size。有什么优雅的方式可以满足我的需求?

header.h

class ChessBoard {
    int matrix[<size>][<size>];
public:
    ChessBoard(int s): <size>(s) {}
};

main.cpp

#include "header.h"
#include <iostream>
int main() {
    std::cout << "Enter the size of the chessboard: ";
    int n;
    std::cin >> n;

    ChessBoard cb(n);

    return 0;
}

【问题讨论】:

    标签: c++ class matrix


    【解决方案1】:

    如果不知道编译时的大小,就无法创建这样的数组。使用指针和 new 创建数组。使用这个数组的孩子将与使用 [][] 相同。唯一的区别是,您需要删除分配的数组,第一个将被“自动”删除。

    int ** matrix = new int*[s];
    for (int i = 0; i < s; i++) 
    {
       matrix[i] = new int[s];
    }
    

    最后delete[] 来自内存的数组

    for (int i = 0; i < s; i++) 
    {
      delete[] matrix[i];
    }
    delete[] matrix;
    

    【讨论】:

    • So.. 在第一个示例中,第 1 行初始化了一个指向数组的指针,而 for 在 @ 的每个框内创建了一个大小为 s 的新数组987654325@数组?
    【解决方案2】:

    为了实例化一个固定大小的矩阵,维度需要是编译时常量。在您的情况下,大小是在运行时确定的。我建议使用std::vector&lt;int&gt;,并在必要时提供双索引访问。 2D 结构只会增加不必要的复杂性:

    class ChessBoard 
    {
      std::vector<int> matrix;
    public:
      int& operator()(size_t row, size_t column) { /* get element from matrix*/ }
      constint& operator()(size_t row, size_t column) const { /* get element from matrix*/ }
      ChessBoard(int s): matrix(s) {}
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      相关资源
      最近更新 更多