c++ - 类对象不能访问自己的私有(private)成员?

标签 c++

所以基本上我的这个类导致了一些大问题:

namespace container {
template<typename T, std::size_t size>
class Array
{
private:
    T m_array[size];

    /* Note: All elements must be of the same type, aka the type used to declare the Array object */
public:
    // Needed to create subarray 
    template<std::size_t previousSize>
    Array(const Array<T, previousSize>& other, int begin, int end)
    {
        assert(begin >= 0 && end < previousSize && "Index must be >= 0 or less than the previous array's size");

        std::size_t index{ 0 };
        do {
            m_array[index] = other.m_array[begin];
            ++begin;
            ++index;
        } while (index < size && begin <= end);

        while (index < size) {
            m_array[index] = T();
            ++index;
        }
    }

    template<std::same_as<T>...Args>
    explicit Array(const Args&... args)
        : m_array{static_cast<T>(args)... }
    {}

在 main() 中,我创建了两个对象:

container::Array<int, 7> myarray{ 200, 500, 300, 499, 1, 10};
std::cout << myarray;
container::Array<int, 5> newArray{ myarray, 2, 4 };
std::cout << newArray;

现在的问题是这一行:

m_array[index] = other.m_array[begin];

看起来“other”无法访问其 m_array 私有(private)成员。 如果我将 m_array 设置为 public,则代码可以正常工作。如果您能帮助我了解问题所在,我将不胜感激。

最佳答案

针对同一问题的一个更简单的示例是:

template <int x>
struct Foo {
    
    template <int y>
    void foo(const Foo<y>& other) {
        value = other.value;
    }

    private:
        int value = 0;
};

int main() {
    Foo<1> a;
    Foo<2> b;
    a.foo(b);  // ERROR ! cannot acces private member
}

这里Foo<1>Foo<2>是两种不同的类型。仅 Foo<1> 的一个实例可以访问 Foo<1> 的私有(private)成员.

您可以使所有实例化彼此成为 friend :

template <int x>
struct Foo {
    
    template <int y>
    void foo(const Foo<y>& other) {
        value = other.value;
    }

    template <int y> friend class Foo;

    private:
        int value = 0;
};

int main() {
    Foo<1> a;
    Foo<2> b;
    a.foo(b);  // OK !
}

线路template <int y> friend class Foo;使 Foo 的每个实例化Foo 的每个其他实例的 friend .

关于c++ - 类对象不能访问自己的私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64975105/

相关文章:

c++ - Linux C++ : apis vs/proc files?

c++ - 模板特化适用于 g++ 但不适用于 Visual C++

c++ - 如何将位图转换为内存中的 PIX?

c++ - 使用 Visual Studio 2008 在 C++ 中链接错误

c++ - 使用基类 :base in body 从类模板派生的类

c++ - 未定义对新 NCURSES 6.1 函数的引用(alloc_pair、reset_color_pairs)

c++ - 如何使用CMake更改构建机器类型

c++ - Visual Studio 2012不同的值发行/ Debug模式

c++ - VC++ 运行时错误 : Debug Assertation Failed

c++ - 从静态功能问题发出信号