我正在嘗試製作一個矩陣程序,它使用整數向量向量生成n * m整數矩陣。但是我很難做到這一點,因爲我對C++相當陌生。我已經開始實施我的程序,但是我收到了一大堆錯誤,我無法弄清楚原因。另外,這是我第一次使用.h和向量,所以請溫柔:)。設計.h和一個.cpp文件C++:錯誤
Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include<vector>
using namespace std;
class Matrix{
public:
Matrix();
Matrix(int r, int c);
void setRow(vector<int> row, int r);
void setColumn(vector<int> col, int c);
int getRow();
int getCol();
void output();
double average();
private:
int row, column;
vector< vector<int> > matrix;
};
#endif
Matrix.cpp
#include "Matrix.h"
#include<iostream>
#include<vector>
using namespace std;
int main(){
int row,column;
cout << "Enter number of rows: ";
cin >> row;
cout << "Enter number of column: ";
cin >> column;
Matrix matrix(row,column);
matrix.output();
}
Matrix::Matrix():row(3), column(3){
matrix = vector<vector<int> >(row);
for (int i = 0; i < row; i++){
matrix[i] = vector<int>(column);
}
}
Matrix::Matrix(int r, int c): row(r), column(c){
matrix = vector<vector<int> >(r);
for (int i = 0; i < r; i++){
matrix[i] = vector<int>(c);
}
}
void Matrix::setRow(vector<int> row, int r){
if (r <= row){
if (row.size <= column){
for (int i = 0; i < row.size; i++){
matrix[r][i] = row[i];
}
}
}
}
void Matrix::setColumn(vector<int> col, int c){
if (c <= column){
if (col.size <= row){
for (int i = 0; i < col.size; i++){
matrix[i][c] = col[i];
}
}
}
}
void Matrix::output(){
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
cout << matrix[i][j];
}
cout<< endl;
}
}
OK所以上面是我以前的代碼固定的版本,但現在我得到這個錯誤:
錯誤:
Matrix.cpp: In member function ‘void Matrix::setRow(std::vector<int, std::allocator<int> >, int)’:
Matrix.cpp:32: error: no match for ‘operator<=’ in ‘r <= row’
Matrix.cpp:33: error: invalid use of member (did you forget the ‘&’ ?)
Matrix.cpp:34: error: invalid use of member (did you forget the ‘&’ ?)
Matrix.cpp: In member function ‘void Matrix::setColumn(std::vector<int, std::allocator<int> >, int)’:
Matrix.cpp:43: error: invalid use of member (did you forget the ‘&’ ?)
Matrix.cpp:44: error: invalid use of member (did you forget the ‘&’ ?)
您不需要在頭文件中包含'#include',並且由於'iostream'是一個非常大的頭文件,所以它會減慢你的編譯時間。 –
sjdowling
2014-11-02 16:53:10
重要信息:[命名include防範](http://stackoverflow.com/q/4867559/103167)和[?什麼是有關在C++標識符使用下劃線的規則](http://stackoverflow.com/q/228783/103167) – 2014-11-02 16:58:59
你不應該在頭文件的全局部分放置'using namespace std;'(最好不要放在其他地方)。 – Galik 2014-11-02 17:22:24