C++ 重载
为什么运算符“[]”上有错误。我想打印矩阵的内容。如果我不能使用括号,我该怎么办 下面是代码示例:C++ 重载,c++,c++11,C++,C++11,为什么运算符“[]”上有错误。我想打印矩阵的内容。如果我不能使用括号,我该怎么办 下面是代码示例: #include <iostream> #include <vector> template <typename T> class Matrix { private: int m; int n; std::vector<T> x; std::vector<std::vector<int>> M
#include <iostream>
#include <vector>
template <typename T>
class Matrix {
private:
int m; int n;
std::vector<T> x;
std::vector<std::vector<int>> Mat;
public:
Matrix (const unsigned int &m, const unsigned int &n, std::vector<T> x);
Matrix(const Matrix &M);
Matrix<T> operator = (const Matrix &M);
// Matrix<T> operator [](const int &index);
friend std::ostream& operator << (std::ostream& os, const Matrix<T> &M) {
os << "[";
for (int i = 0; i< M.m; i++){
for (int j = 0; j< M.n; j++){
os << M[i][j] << ' ';
}
os << '\n';
}
os << "]\n";
return os;
}
};
我已经纠正了错误。但它不会打印我的矩阵。
这是我的主要观点:
int main(){
std::vector<int> x = {1,2,3,4};
Matrix<int> A{2,2,x};
Matrix<int> B{2,2,x};
std::cout << A;
std::cout << B;
return 0;
}
这是我的构造函数,我需要从一个向量中生成一个矩阵,在这里我指定行和列
template <typename T>
Matrix<T>::Matrix (const unsigned int &m, const unsigned int &n, std::vector<T> x){ //constructor
this -> m = m;
this -> n = n;
this -> x = x;
int index = 0;
for (int i = 0; i<m; i++){
for (int j = 0; j<n; j++){
Mat[i][j] = x[index];
index++;
}
}
}
运算符[]返回一个矩阵。您应该将其更改为模板值。问题是这一行:
os << M[i][j] << ' ';
编辑:
根据您更新的代码,您可能会遇到一个很好的SIGSEGV错误分段错误问题。为什么?易于理解的您没有调整数据成员的大小
你必须这样做:
template <typename T>
Matrix<T>::Matrix (const unsigned int &m, const unsigned int &n, std::vector<T> x){ //constructor
this -> m = m;
this -> n = n;
this -> x = x;
int index = 0;
// resizing Matrix according to our need i.e. m rows and n columns
Mat.resize(m);
for (unsigned int i = 0; i < Mat.size(); i++) {
Mat[i].resize(n);
}
for (unsigned int i = 0; i<m; i++){
for (unsigned int j = 0; j<n; j++){
Mat[i][j] = x[index];
index++;
}
}
}
您的代码中有不同的错误: 1.-你的建造师:
Matrix<T>::Matrix (const unsigned int &m, const unsigned int &n, std::vector<T> x)
使用向量x很容易
2.-要写出所有元素,你可以写以下内容:
std::ostream& operator << (std::ostream& os, const Matrix<T>& M) {
os << "[";
for (int i = 0; i< M.rows(); ++i){
for (int j = 0; j< M.cols(); ++j){
os << M(i, j) << ' ';
}
os << '\n';
}
os << "]\n";
return os;
}
如果您定义行和列,那么这不是友元函数 我想建议您添加更多信息。在这种情况下,一行程序永远不会有用。顺便说一下,我只需要把矩阵做对就行了?现在没有错误,但问题是,它没有输出结果。“怎么可能呢?”签上“是”。您只需做以下更改:os@Sign我没有看到您更新的问题。参考我的最新答案。现在,它应该起作用了。很多thanks@Kunal普里。你是最棒的!!!!它确实打印了我的矩阵。我非常感谢你在这里。
Matrix<T>::Matrix (unsigned int m, unsigned int n, const std::vector<T>& x)
Matrix<T>::Matrix (unsigned int m0, unsigned int n0, const std::vector<T>& x0)
: m{m0}, n{n0}, x{x0} {...}
Matrix& operator()(unsigned int i, unsigned int j);
std::ostream& operator << (std::ostream& os, const Matrix<T>& M) {
os << "[";
for (int i = 0; i< M.rows(); ++i){
for (int j = 0; j< M.cols(); ++j){
os << M(i, j) << ' ';
}
os << '\n';
}
os << "]\n";
return os;
}