类arrray [3] [3]中的存取器和mutator c ++方法

时间:2019-03-24 15:39:44

标签: c++

我是一名初学者程序员,我对任务有疑问。我必须使用set(),get()方法来初始化矩阵[3] [3]的元素,但我必须对所有元素都采用通用方法。

请帮助!

//mat3.hpp

class mat3 {

public:

    mat3(); //Default constructor, double loop initialize 0.0

    mat3(float v11, float v12, float v13,
        float v21, float v22, float v23,
        float v31, float v32, float v33);//Constructor with arguments

    void print(); //Method printing matrix

private:

    float data[3][3];

};

2 个答案:

答案 0 :(得分:0)

getter / setter方法:

void setElement(const unsigned row, const unsigned col, const float value) 
{data[row][col] = value;}

float getElement(const unsigned row, const unsigned col) const
{return data[row][col];}

最好检查传递到getter / setter函数中的行和列索引是否在范围之内,您可以使用assert进行此操作。

答案 1 :(得分:0)

请与您的讲师联系,以确保您是否可以跨通用并结合使用setter和getter:

float & operator(int row, int column) 
{ 
    return data[row][column]; 
}

()运算符使您可以像函数一样使用对象。这两个参数提供了数组查找的坐标。该功能返回对所请求数组元素的引用,因此您可以对其进行设置或将其添加到您的内心深处。

用法

float x = mymat(1,2); 

作为吸气剂或

mymat(1,2) = 3.14; 

作为二传手。为了进行调试,您可能需要添加测试以确保rowcolumn不在范围之内。您可能还想返回const版本

float operator(int row, int column) const
{ 
    return data[row][column]; 
}

用于只读对象。显然,这不能作为二传手。

如果无法使用此方法,您仍然可以采用基本思路,并传递要获取或设置为参数的坐标。