c++ - 为什么我的重载转换运算符无法访问私有(private)成员?

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

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

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

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

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

ma​​in.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;
}

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

为什么会发生这种情况?我可以采取什么措施来纠正它?

最佳答案

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

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

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

    template<class E> friend class array2d;

    /* ... */
};

顺便说一句,我不太确定是否

delete [] newData;

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

关于c++ - 为什么我的重载转换运算符无法访问私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55461296/

相关文章:

c++ - 整数类型,就像没有隐式转换的本地类型

c++ - 同名的 typedef 和模板参数

c# - 类型转换的通用方法

python - Django 模板中两个 block 之间的可变上下文?

java - 双型比较器

c# - C#中的自动类型转换

c++ - 注册 Clang Checker : "out-of-line-definition of register" 时出错

c++ - 找不到“iostream”文件

c++ - Friend 模板函数(在非模板类中),C++

php - Drupal 元素类