构造一个空矩阵
Construct an empty matrix
本文关键字:一个 更新时间:2023-10-16
我有一个类
class A
{
int *const e;
const int row, column;
public:
A(int r, int c); // create a empty matrix with r rows and c columns passed in method
}
int main(int argc, char* argv[])
{
A test(2,2);
return 0;
}
问题是我如何编写一个构造函数来创建我可以使用的矩阵?
你的构造函数就是
A::A(int r, int c) : row{r}, column{c}
{
e = new int[r * c];
}
那么你的析构函数应该是
A::~A()
{
delete[] e;
}
您可以访问元素作为
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < column; ++j)
{
std::cout << e[i * row + j] << " "; // Using array arithmetic
}
std::cout << std::endl;
}
你的问题听起来像:如何将参数保存到常量行/列属性中。
A::A(int r, int c): row(r), column(c), e(new int[r*c])
{
for (int i=0; i<r*c; i++) e[i]=0;
}
也不要忘记析构函数:
virtual ~A(){ delete[] e; };
在构造函数的参数列表中,参数按声明顺序初始化,因此不能使用行/列(它们尚未初始化)。
你需要一个指向指针的指针来创建 [普通] 二维数组所以
int ** const e;
然后构造函数可以像这样工作:
e = (int**) malloc(sizeof(int**) * a);
for(int i=0;i<a;++i) {
e[i] = (int*) malloc(sizeof(int*) * b);
}
您的下一个问题是"如何初始化常量"。为此,您可以参考此处的答案:如何在类C++中初始化常量成员变量
要实现这一点,请将初始化器代码放在一个函数中:
initConstArray(const int** const a, int r, int c) {
e = (int**) malloc(sizeof(int**) * a);
for(int i=0;i<r;++i) {
e[i] = (int*) malloc(sizeof(int*) * b);
for(int j = 0;j < c; ++j) {
e[i][j] = a[i][j];
}
并从构造函数初始值设定项列表中调用此函数:
A(int **a, int r, int c) : initConstArray(a, r, c) {
}
以下是使用模板实现矩阵的另一种方法:
#include <array>
#include <iostream>
template <std::size_t ROW, std::size_t COLUMN>
class A
{
std::array<int, ROW*COLUMN> a;
public:
A():a(){};
};
int main(int argc, char* argv[])
{
A<3,3> test;
//test.printSize();
//std::cout << test;
return 0;
}
更短更干净。
要使注释行正常工作,必须向类中添加以下 2 个函数:
void printSize(){ std::cout << ROW << "x" << COLUMN << std::endl; };
friend std::ostream& operator<<( std::ostream& os, A<R,C> mat){
int col_count = 0;
for (auto id=mat.a.begin(); id!=mat.a.end(); id++){
os << *id << (++col_count%C==0?"n":" ");
}
return os;
};
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '