关于 C++ 上虚拟运算符*的问题
我试图在 C++ 上创建虚拟运算符
class Data
{
virtual Matrix operator* (Matrix &_matrix);
virtual Scalar operator* (Scalar &_scalar);
};
class Matrix : public Data
{
private:
vector<vector<double>> data;
public:
// ...
Matrix operator* (Matrix &_matrix);
};
class Scalar : public Data
{
private:
double data;
public:
// ...
Scalar operator* (Scalar &_scalar);
};
,问题是,当我创建如下所示的 Data* 数组时
Data* arr[10];
arr[0] = new Matrix(3,3);
arr[1] = new Matrix(3,3);
arr[0]->operator*(arr[1]);
,我无法在这两个矩阵之间进行乘法,因为我无法将 Data 作为参数传递。 但问题是,我无法使函数的参数采用 Data* 类型,因为它将无法访问 Matrix 或 Scalar 对象的私有成员。
遇到这种奇怪的情况该如何处理呢?
I was trying to make virtual operator on C++
class Data
{
virtual Matrix operator* (Matrix &_matrix);
virtual Scalar operator* (Scalar &_scalar);
};
class Matrix : public Data
{
private:
vector<vector<double>> data;
public:
// ...
Matrix operator* (Matrix &_matrix);
};
class Scalar : public Data
{
private:
double data;
public:
// ...
Scalar operator* (Scalar &_scalar);
};
And the problem was, when I created Data* Array like below
Data* arr[10];
arr[0] = new Matrix(3,3);
arr[1] = new Matrix(3,3);
arr[0]->operator*(arr[1]);
I could not do multiplication between these two matrices, since I cannot pass Data as an argument.
But the problem is, I cannot make the function's argument to take Data* type because, it will not be able to access private members of Matrix or Scalar objects.
How to deal with this kind of weird situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类双重调度问题 - 参见 Meyer 的(忘了是哪一个)。
您需要运算符在左侧和右侧都是虚拟的,因此您需要两个虚拟调用:
我已经掩盖了返回类型和内存管理的问题。与通常的运算符一样,您最好将
*=
定义为原语。然后,这可以返回对*this
的引用。然后可以根据*=
定义*
运算符。再说一次,这是在“Effective C++”中。Class double dispatch problem - See Meyer's (forget which one).
You need the operator to be virtual on both the lhs and rhs, so you need two virtual calls:
I've glossed over the issue of the return type and memory management. As usual with operators, you might be better defining
*=
as the primitive. This can then return a reference to*this
. The*
operator can then defined in terms of*=
. Once again, this is in "Effective C++".这个问题的解决方案称为 Double Dispatch,这在 C++ 中有点奇怪。下面的代码展示了这个技巧的工作原理:
The solution to this is called Double Dispatch which is a little strange in C++. The following code shows how this trick works: