为什么我超负荷的铸造操作员无法访问私人成员
Why does my overloaded casting operator not have access to private members?
我正在尝试使用类型 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[]
,您将有未定义的行为。
相关文章:
- C++ 传递指向对象的指针的指针,无法访问成员
- 从不同C++类的成员变量访问成员函数
- 使用 getter 访问成员变量C++
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- 通过多个类访问成员时出错
- 如何在使用对象指针时访问成员函数
- 为什么相应成员不能正确访问成员函数指针
- 从两个不同类继承的非虚拟基类的访问成员
- 如何使用 gcc 内联汇编器代码访问成员变量
- 如何使用常数向量访问成员函数
- 访问成员函数中参数的类成员
- C++嵌套结构初始化和访问成员
- 通过指向班级第一个成员的指针访问成员是不确定的行为吗?
- 如何使用C STD :: SET中的迭代器访问成员功能
- 访问成员C 时,结构的向量生成了范围的错误
- 带指针的班级访问成员
- 从聚合类访问成员变量
- 如何访问成员变量 sqlite 回调
- ctypes/C++segfault访问成员变量
- 通过父类型的指针或直接从派生类访问成员函数的差异