所以这是我第一次尝试使用 C++ 中的类编写程序。作为练习,我正在尝试创建一个可以执行某些操作的二维数组类。这是我的类必须能够运行的 main.cpp 中的一部分代码。
int main()
{
array2d<double> ar(2,2);
ar(1,1) = 1;
ar(0,0) = 2;
ar(0,1) = 3;
ar(1,0) = 4;
auto X{ar};
array2d<double> c(2,2);
c = ar;
c.diagonal(1) = 5; //c(1,1) = 5
}
这是我的代码。我在对角线函数中遇到错误“错误:左值需要作为赋值的左操作数”。我不知道我应该做什么。此函数的目的是在数组的对角线元素中赋值。
template<typename T>
class array2d
{
private:
int n,m;
vector<T> vec;
public:
array2d(int M, int N)
: n{N}, m{M}
{
vector<T> vec1(n*m);
vec = vec1;
}
array2d(array2d<T> &arr)
: n{arr.N()} , m{arr.M()}
{
vec = arr.V();
}
array2d &operator=(array2d<T> & arr){
vec = arr.V();
return *this;
}
T &operator()(int i,int j)
{
auto it = vec.begin();
it += i*n+j;
return *it;
}
T diagonal(int a)
{
auto x= *this;
return x(a,a);
}
int M (){return m;}
int N (){return n;}
vector<T> V(){return vec;}
};
编辑:我还有一个问题。接下来我的类应该能够运行的是这个
ar = X.transpose();
但我收到 2 个错误:
错误:从“array2d”类型的右值对“array2d&”类型的非常量引用进行无效初始化 和
注意:初始化“array2d array2d::operator=(array2d&) [with T = double]”的参数 1|
我的功能是这样的。
array2d<T> transpose ()
{
auto &y = *this ;
array2d<T> x(y.N(),y.M()) ;
for (int i{0};i<x.d1();i++){
for (int j{0}; j<x.d2();j++){
x(i,j) = y(j,i);
}
};
return x;
}
最佳答案
我进行了各种更改并在代码中添加了注释:
// bad practice:
// using namespace std;
template<typename T>
class array2d {
private:
// use an unsigned int for dimensions
unsigned m, n;
std::vector<T> vec;
public:
// initialize the vector in the member initializer list too:
array2d(unsigned M, unsigned N) : m{M}, n{N}, vec(m * n)
{}
// arr should be a const&:
array2d(const array2d<T>& arr) : m{arr.m}, n{arr.n}, vec(arr.vec)
{}
// arr should be a const&:
array2d& operator=(const array2d<T>& arr) {
vec = arr.vec;
// n and m should also be copied:
m = arr.m;
n = arr.n;
return *this;
}
T& operator()(unsigned i, unsigned j) {
// unnecessary iterator arithmetic replaced
return vec[i * n + j];
}
// a const version to be used in const contexts:
const T& operator()(unsigned i, unsigned j) const {
return vec[i * n + j];
}
// You should return a T& and it should be a reference to
// a T inside vec, not to a copy that will become invalid as soon as the function
// returns.
T& diagonal(unsigned a) {
return (*this)(a, a);
}
// this function should be const since you are not supposed to change "this"
array2d<T> transpose() const {
// y is just confusing
// auto& y = *this;
// Use your member variables (or call the functions M() and N()) directly.
array2d<T> x(n, m);
// d1() and d2() doesn't exist in the code you've shown, but they are not
// needed:
for(unsigned i = 0; i < x.m; i++) {
for(unsigned j = 0; j < x.n; j++) {
x(i, j) = (*this)(j, i);
}
}
return x;
}
unsigned M() { return m; }
unsigned N() { return n; }
std::vector<T> V() { return vec; }
};
关于c++ - 我无法为二维数组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515242/