无法为我的自定义类的对象赋值,该值的行为应类似于矩阵
Can't assign a value to object of my custom class, that shall behave like a matrix
我有自定义类,它的行为像矩阵。除了从同一类的其他实例赋值之外,一切都运行良好。
我可以这样写:
Matrix a(5,7);
// du stuff with a
Matrix b(5,7);
Matrix d=a+b;
d=a*5;
d[3][2]=1;
//but I can't do this:
double x=d[3][2];
//at this point I get this error:
main.cpp:604:12: error: passing ‘const Matrix’ as ‘this’ argument of ‘Matrix::Proxy Matrix::operator[](int)’ discards qualifiers
有没有人知道如何解决这个问题?(
矩阵类的实现在这里:
class Matrix {
public:
Matrix(int x, int y);
~Matrix(void);
//overloaded operators
Matrix operator+(const Matrix &matrix) const;
Matrix operator-() const;
Matrix operator-(const Matrix &matrix) const;
Matrix operator*(const double x) const;
Matrix operator*(const Matrix &matrix) const;
friend istream& operator>>(istream &in, Matrix& a);
class Proxy {
Matrix& _a;
int _i;
public:
Proxy(Matrix& a, int i) : _a(a), _i(i) {
}
double& operator[](int j) {
return _a._arrayofarrays[_i][j];
}
};
Proxy operator[](int i) {
return Proxy(*this, i);
}
// copy constructor
Matrix(const Matrix& other) : _arrayofarrays() {
_arrayofarrays = new double*[other.x ];
for (int i = 0; i != other.x; i++)
_arrayofarrays[i] = new double[other.y];
for (int i = 0; i != other.x; i++)
for (int j = 0; j != other.y; j++)
_arrayofarrays[i][j] = other._arrayofarrays[i][j];
x = other.x;
y = other.y;
}
int x, y;
double** _arrayofarrays;
};
您目前有一个operator[]
签名:
Proxy operator[](Matrix *this, int i)
你想调用这个:
Proxy operator[](const Matrix *, int)
错误是说为了从const Matrix *
转换到Matrix *
, const
必须被丢弃,这是不好的。您应该在类中提供const
版本:
Proxy operator[](int) const {...}
在你的类中,它获得this
的第一个参数,并且在参数列表之后的const
意味着第一个参数将是一个指向你的类的常量对象的指针,而不是一个非常量对象。
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 用C++中的sscanf赋值
- 类似于strcat()的函数出现问题
- 为std::string的某个索引赋值
- 重载Singly Linked List中的赋值运算符
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 创建类似于布尔值的变量类型
- 等价于将c++上的char赋值给c#
- 复制<Interface>作用类似于值的类的shared_ptr
- 我可以在 ANTLR4 中使用类似于 c++ 的虚拟令牌(具有相同返回值的令牌)吗?
- 通过访问二维数组实现双线性插值的概念类似于一维数组
- 重载C++赋值运算符,使其行为类似Java
- C++-对象图的哈希值类似于boost::序列化
- Int 值奇怪地类似于指针
- 在c++中如何创建类似于snprintf的消息,并只更改消息中的值
- Boost::noncopyable_::noncopyable类似于move构造函数/赋值
- c++的引用赋值相当于PHP
- 无法为我的自定义类的对象赋值,该值的行为应类似于矩阵
- 在索引和值"for i, v in enumerate(listVar):"上是否有 C++/C++11 类似于 python 迭代?