为什么重载的铸造操作员无法访问私有成员?

时间:2019-04-01 18:19:05

标签: c++ templates casting operator-overloading private-members

我正在尝试使用类型array2d在模板化的T类上实现重载的转换运算符。因此,我将从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;
}

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

为什么会发生这种情况,我该如何纠正?

1 个答案:

答案 0 :(得分:2)

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

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

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

    template<class E> friend class array2d;

    /* ... */
};

作为旁注,我不太确定

delete [] newData;

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