为什么我的重载转换运算符无法访问私有成员?

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

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

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

的私有成员

这是我到目前为止的情况(为简洁起见,删除了不相关的代码)

array2d.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;
}

main.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> 是不同的类型,默认情况下,两个不同 classes 的两个实例无法访问它们的私有成员。

您可以通过将 array2d 的每个实例声明为模板 array2d 的好友 class 来解决此问题:

template<typename T>
class array2d {
    /* ... */

    template<class E> friend class array2d;

    /* ... */
};

附带说明一下,我不太确定

delete [] newData;

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