C++ 使用矢量重载<<时出错
C++ Error in overloading << with using vectors
我正试图通过使用向量和<lt;操作人员问题是,当我尝试运行代码时,我收到一个错误,说MatrixViaVector中没有名为size的成员。
在我的头文件中,我有:
#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????????
}
您的MatrixViaVector<>
没有函数size()
,但如果您打算使用向量的大小,请执行以下操作:
更改此代码段:
for (int i = 0; i < obj.size(); i++){
for (int j = 0; j < obj.capacity(); j++)
outs << " "<< obj.matrix[i][j];
outs<<endl;
}
至
for (std::vector<int>::size_type i = 0; i < obj.matrix.size(); i++){
for (std::vector<int>::size_type j = 0; j < obj.matrix.size(); j++)
outs << " "<< obj.matrix[i][j];
outs<<endl;
}
std::vector::size((和std::vector::capacity((是两个不同的函数,请检查其区别。
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 呼叫运营商<<临时
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为x86而非x64编译时出错
- <<操作员在下面的行中工作
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了