【问题标题】:Template function inside template class "is private within this context" error模板类中的模板函数“在此上下文中是私有的”错误
【发布时间】: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


【解决方案1】:

请记住,每个MyArray 特化都是它自己的独立类。一个类总是可以访问它自己的成员,但MyArray&lt;int&gt;MyArray&lt;long&gt; 不能访问彼此的成员!

我会将这个operator+ 设为非会员friend。将成员函数正确地加为好友通常是困难的,甚至是不可能的,而且使对称运算符(如二元 + 非成员)还有其他好处。只要涉及到的三个类都是函数模板的友元,就可以使用它们的成员。

template <typename T>
class MyArray {
    // ...

    template <typename A, typename B>
    friend auto operator+(const MyArray<A>& arr1, const MyArray<B>& arr2)
        -> MyArray<decltype(arr1[0] + arr2[0])>
    {
        // ...
    }
};

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多