需要在C++项目中定义一个行数和列数可变的"表格"对象,这样写可以吗?


class cell
{
    public:
    double ratio_ampCell_amp0dB;//单元格中存放的数据
}//单元格

class sheet :
{
    public:
    int count_key;//行数
    int number_harmonic_max;//列数
    cell[count_key][number_harmonic_max];//以单元格为元素的数组
}//工作表

以下内容部分参考ChatGPT模型:


可以这样定义一个宽高可变的表格对象:

class Cell
{
public:
    double data; // 单元格中存放的数据
};

class Sheet
{
public:
    Sheet(size_t rowCount, size_t colCount)
        : m_rowCount(rowCount), m_colCount(colCount)
    {
        m_cells.resize(rowCount * colCount);
    }

    Cell& getCell(size_t row, size_t col)
    {
        return m_cells[row * m_colCount + col];
    }

    const Cell& getCell(size_t row, size_t col) const
    {
        return m_cells[row * m_colCount + col];
    }

    size_t getRowCount() const
    {
        return m_rowCount;
    }

    size_t getColumnCount() const
    {
        return m_colCount;
    }

private:
    std::vector<Cell> m_cells;
    size_t m_rowCount;
    size_t m_colCount;
};

这里用 std::vector 存储所有单元格的数据,可以通过 getCell() 方法来获取指定位置的单元格对象,getRowcount() 和 getColumnCount() 方法用于获取表格的行数和列数。需要注意的是,在 Sheet 类的构造函数中需要指定表格的行数和列数,因为 std::vector 在构造时需要指定大小。


如果我的建议对您有帮助、请点击采纳、祝您生活愉快

单元格可以有高度和宽度属性,但是每一行的高度是一样的,对于同一个表格,所有行中的列数是一样的。
所以,定义的类至少应该包括:单元格、行、表格
参考如下:

#include <iostream>
using namespace std;

#define MAXCOLNMB (int)100
#define MAXROWNMB (int)999999
class cell
{
public:
    int rowId, colId; //行号和列号
    double ratio_ampCell_amp0dB;//单元格中存放的数据

    int width; //单元格宽度
    int height; //单元格高度

    void setWidth(int w) { width = w; }
    void setHeight(int h) { height = h; }

};


class row
{
public:
    int height; //行高
    cell cells[MAXCOLNMB]; //保存本行所有的单元格
    static int nmb; //实际单元格个数,所有行的列数相同

    //同一行的所有单元格共用一个行高
    void setHeight(int h) 
    { 
        height = h; 
        for (int i = 0; i < nmb; i++)
            cells[i].setHeight(h);
    }
    //设置单元格个数
    static void setColNmb(int n) { nmb = n; }
};

class sheet
{
public:
    int count_key;//实际行数
    int number_harmonic_max;//实际列数
    
    row allrows[MAXROWNMB];
    
};

你那样写不行,可以用 vector<vector<cell>> 代替数组

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632