为什么我超负荷的铸造操作员无法访问私人成员

Why does my overloaded casting operator not have access to private members?

本文关键字:访问 成员 操作员 超负荷 为什么      更新时间:2023-10-16

我正在尝试使用类型 T 在我的模板化array2d类上实现重载的转换运算符。所以我要从array2d<T>投到一个新的array2d<E>.

我能够执行强制转换本身,但是当我尝试将转换数据设置为array2d<E>的新实例时出现问题。编译器告诉我,强制转换运算符无权访问 array2d 的私有成员

这是我到目前为止所处的位置(为简洁起见,编辑掉了不相关的代码(

阵列2d.h

template<typename T>
class array2d {
private:
    // Member Variables
    T** data;
    size_t width, height;
public:
    // constructors, methods, etc...
    // Cast Operator
    template<typename E>
    operator array2d<E>() const;
};
// Other overloaded operators...
// Overloaded Casting Operator
template<typename T>
template<typename E>
array2d<T>::operator array2d<E>() const{
    // Create new instance
    array2d<E> castedArr(width, height);
    // Allocate memory for the casted data, then cast each element
    E** newData = new E*[castedArr.get_height()];
    for (size_t i = 0; i < castedArr.get_height(); i++){
        newData[i] = new E[castedArr.get_width()];
        for (size_t j = 0; j < castedArr.get_width(); j++){
            newData[i][j] = (E)data[i][j];
        }
    }
    // issue here, can't set data because it's private.
    castedArr.data = newData;
    delete [] newData;
    newData = nullptr;
    return castedArr;
}

主.cpp

#include "array2d.h"
int main(int argc, char *argv[]) {
// Cast Operator
    // Create an array2d<T> of
    // width = 5
    // height = 5
    // fill all elements with 42.1
    array2d<double> x(5, 5, 42.1);
    // Create a new array exactly the same as
    // x, where x is casted to int
    array2d<int> y = (array2d<int>) x;
    return 0;
}

这让我感到困惑,因为我还有许多其他重载的运算符,它们可以使用几乎完全相同的逻辑很好地访问私有成员。

为什么会发生这种情况,我该怎么做才能纠正它?

编写模板时,您不会确定实际类型,而是为不同类型的蓝图创建蓝图。 array2d<double>array2d<int> 是不同的类型,默认情况下,两个不同类的两个实例无法访问其私有成员。

您可以通过声明模板array2d友元类的每个实例来解决此问题array2d

template<typename T>
class array2d {
    /* ... */
    template<class E> friend class array2d;
    /* ... */
};

作为旁注,我不太确定

delete [] newData;

是个好主意。您正在销毁新array2d实例应管理的部分资源。如果您在 array2d::~array2d() 中再次delete[],您将有未定义的行为。