【发布时间】:2018-03-16 02:58:17
【问题描述】:
我正在尝试构建我自己的 Matrix 类型,该类型的行为符合标准 C 矩阵与多维数组。到目前为止,这是我的实现:
#include <iostream>
/**
* To build it use:
* g++ -std=c++11 test_template_initicialization.cpp -o main
*/
template <int width, int height>
struct Matrix
{
long int _data[height][width];
Matrix()
{
}
Matrix(long int matrix[height][width]) : _data(matrix)
{
}
/**
* Overloads the `[]` array access operator, allowing you to access this class objects as the
* where usual `C` arrays.
*
* @param line the current line you want to access
* @return a pointer to the current line
*/
long int* operator[](int line)
{
return this->_data[line];
}
/**
* Prints a more beauty version of the matrix when called on `std::cout<< matrix << std::end;`
*/
friend std::ostream &operator<<( std::ostream &output, const Matrix &matrix )
{
int i, j;
for( i=0; i < height; i++ )
{
for( j=0; j < width; j++ )
{
output << matrix._data[i][j] << ", ";
}
output << matrix._data[i][j] << "\n";
}
return output;
}
};
/**
* C++ Matrix Class
* https://stackoverflow.com/questions/2076624/c-matrix-class
*/
int main (int argc, char *argv[])
{
Matrix<3, 3> matrix;
std::cout << matrix << std::endl;
matrix[0][0] = 911;
std::cout << matrix << std::endl;
std::cout << matrix[0] << std::endl;
std::cout << matrix[0][0] << std::endl;
Matrix<4,4> matrix2 = { 0 };
}
在构建最后一个示例 Matrix<4,4> matrix2 = { 0 }; 时,出现类型不兼容错误:
D:\test_template_initicialization.cpp: In instantiation of 'Matrix<width, height>::Matrix(long int (*)[width]) [with int width = 4; int height = 4]':
D:\test_template_initicialization.cpp:67:29: required from here
D:\test_template_initicialization.cpp:16:56: error: incompatible types in assignment of 'long int (*)[4]' to 'long int [4][4]'
Matrix(long int matrix[height][width]) : _data(matrix)
错误的主要部分是'long int (*)[4]' to 'long int [4][4]'。 long int (*)[4] 来自matrix2 = { 0 };,long int [4][4] 是我的标准类模板声明long int _data[height][width];。
我能否修复我的Matrix 构造函数,使其可以接受来自matrix2 = { 0 }; 初始化调用的long int (*)[4]?
【问题讨论】:
-
前几天有人问同样的问题,我在SE上找到了答案,但现在找不到了。其中有很多非常相似,也许其中一个会给你一个线索。对于初学者,请参阅stackoverflow.com/questions/46687424/…。
-
您在这里遇到的具体问题正是编译器所说的:您无法将
int *(您传入的内容)转换为long *(构造函数采用的内容)。您还有其他使事情复杂化的问题(例如,您的复制构造函数不会按照您的想法执行),但首先要让您的类型保持一致。 -
抱歉,我没有阅读我在标题后面发布的最后一个链接。那完全不是我的本意。我的意思是更像这个:stackoverflow.com/questions/34778847/…
标签: c++ arrays c++11 matrix multidimensional-array