我创建了一个2D向量(0,0(,并希望调整它的大小(n,m(,但是,我的调整大小函数必须保持const
我试过做
void resize(int row, int col) const
{
array.resize(row, vector<int>(col));
}
但不断得到
passing ‘const std::vector<std::vector<int>, std::allocator<std::vector<int> > >’ as ‘this’ argument discards qualifiers
我该怎么做?
矩阵.h
#pragma once
#include <vector>
using namespace std;
template <typename Object>
class matrix
{
public:
matrix(int rows, int cols) : array{ rows } {
for (auto& thisRow : array)
thisRow.resize(cols);
}
matrix( initializer_list<vector<Object>> lst ) : array( lst.size( ) )
{
int i = 0;
for( auto & v : lst )
array[ i++ ] = std::move( v );
}
matrix( const vector<vector<Object>> & v ) : array{ v } {}
matrix( vector<vector<Object>> && v ) : array{ std::move( v ) } {}
matrix() {}
const vector<Object> & operator[]( int row ) const
{
return array[ row ];
}
vector<Object> & operator[]( int row )
{
return array[ row ];
}
int numrows() const
{
return array.size( );
}
int numcols() const
{
return numrows( ) ? array[ 0 ].size( ) : 0;
}
void resize(int row, int col) const
{
array.resize(row, vector<int>(col));
}
private:
vector<vector<Object>> array;
};
main.cpp
matrix<int> mat = matrix<int>();
cout << "Zero-parameter matrix (rows,cols) = (" << mat.numrows() << "," << mat.numcols() << ")" << endl;
mat.resize(4, 3);
cout << "Resized matrix to 4x3" << endl;
cout << mat << endl;
mat[2][1] = 12;
cout << "Modified (2,1)" << endl;
cout << mat << endl;
当你把const
放在函数的末尾时,你说隐含的this
是const。也就是说,你承诺不修改这个函数被调用的对象的状态
但是调用resize()
来修改对象状态的整个点不是吗?如果我是你,我会把const
从那里拿走。
换句话说,您有两种选择:要么信守承诺不更改对象的状态(可能是通过返回调整大小的副本?(,要么丢失const
。