【发布时间】:2020-04-26 13:35:51
【问题描述】:
我正在尝试编写我自己的类,它应该代表一个模板化数组。我想为它定义 operator+,但它可以添加两个指定为不同类型的数组(当然,如果一个可以提升到另一个,反之亦然)。为了做到这一点,我必须对运算符进行模板化定义(那是个好方法吗?),编译后我的编译器报告说,基本上,据我所知,找不到我的任何状态成员班级。代码低于任何赞赏的帮助......因为当所有内容都公开时,代码工作得非常好,但显然这不是重点。
MyArray.hpp: In instantiation of ‘MyArray<decltype ((((MyArray<T>*)this)->MyArray<T>::ptr[0] + other[0]))> MyArray<T>::operator+(const MyArray<A>&) [with A = int; T = double; decltype ((((MyArray<T>*)this)->MyArray<T>::ptr[0] + other[0])) = double]’:
test3.cpp:65:3: required from here
MyArray.hpp:94:32: error: ‘int* MyArray<int>::ptr’ is private within this context
tmp[i] = ptr[i] + (other.ptr)[i];
~~~~~~~^~~~
MojNiz.hpp:9:12: note: declared private here
T* ptr = nullptr;
#include <iostream>
template <typename T>
class MyArray {
private:
T* ptr = nullptr;
size_t arraySize = 0;
size_t maxCapacity = 0;
public:
template <typename A>
auto operator+(const MyArray<A>& other)-> MyArray<decltype(ptr[0] + other[0])> {
if (arraySize != other.size()) throw std::invalid_argument("Nope");
MyArray<decltype(ptr[0] + other[0])> tmp;
tmp.ptr = new decltype(ptr[0] + other[0])[arraySize];
tmp.arraySize = arraySize;
for (int i = 0; i < arraySize; ++i) {
tmp[i] = ptr[i] + (other.ptr)[i];
}
return tmp;
}
【问题讨论】:
-
请同时粘贴完整的编译器错误消息。此外,
other[0]意味着operator[]- 有吗? -
@aschepler,谢谢,我添加了编译器错误消息。是的,我的班级有 operator[] 和所有其他的花里胡哨。基本上我想说的是,如果我将 state 声明为 public,我的代码可以完美运行
标签: class templates private friend