3
我试图通过使用向量和< <运算符来显示基本3乘3矩阵。问题是,当我尝试运行代码时,出现一个错误,指出在MatrixViaVector中没有成员命名大小。C++重载错误<<使用向量
在我的头文件我有:
#ifndef homework7_MatrixViaVector_h
#define homework7_MatrixViaVector_h
#include<iostream>
#include<fstream>
#include<string>
#include <cstdlib>
#include <vector>
using namespace std;
template <class T>
class MatrixViaVector{
public:
MatrixViaVector();
MatrixViaVector(int m,int n);
template <class H>
friend ostream& operator <<(ostream& outs, const MatrixViaVector<H> &obj);
private:
int m,n;
vector<vector<T>> matrix;
};
#endif
而且在我的测试文件我有:
#include "MatrixViaVector.h"
template <class T>
MatrixViaVector<T>::MatrixViaVector(){
//creates a 3 by 3 matrix with elements equal to 0
for (int i=0;i<3;i++){
vector<int> row;
for (int j=0;j<3;j++)
row.push_back(0);
matrix.push_back(row);
}
}
template <class T>
MatrixViaVector<T>::MatrixViaVector(int m,int n)//creates a m by n matrix????
{
//creates a matrix with dimensions m and n with elements equal to 0
for (int i=0;i<m;i++){
vector<int> row;
for (int j=0;j<n;j++)
row.push_back(0);
matrix.push_back(row);
}
}
template <class T>
ostream& operator <<(ostream& outs, const MatrixViaVector<T> & obj)
{
//obj shud have the vector and therefore I should be able to use its size
for (int i = 0; i < obj.size(); i++){
for (int j = 0; j < obj.capacity(); j++)
outs << " "<< obj.matrix[i][j];
outs<<endl;
}
outs<<endl;
return outs;
}
int main()
{
MatrixViaVector <int> A;
MatrixViaVector <int> Az(3,2);//created an object with dimensions 3by2????
cout<<A<<endl;
cout<<Az<<endl;//this prints out a 3 by 3 matrix which i dont get????????
}
@CaptainObvlious谢谢更正 – Steephen
如果尺寸不同,该怎么办?像3而不是3乘3,我们有3乘2,那么for循环将如何改变? – Brogrammer
@guploo将不会有任何变化,因为vector <>的边界正在使用vector <> :: size()函数检查 – Steephen