首页 > 解决方案 > 复制和移动构造函数是自动朋友吗?

问题描述

当我们定义复制或移动构造函数时,我们可以访问另一个类的私有变量。C ++会friend自动将它们相互连接吗?

例如:

my_str::my_str(my_str&& m) 
{
    size_ = m.size_; //accessing private variable another my_str class
    buff_ = m.buff_; //accessing private variable another my_str class
    m.buff_ = nullptr;
    m.size_ = 0;
}

标签: c++friend-class

解决方案


它不被认为是朋友,但是是的,类的任何成员函数都my_str可以访问 type 的所有实例的私有成员my_str,而不仅仅是this实例:

class my_str {
    void foo(my_str& other) {
        // can access private members of both this-> and other.
    }

    static void bar(my_str& other) {
        // can access private members of other.
    }
};

其背后的总体思想是允许 2 个或多个相同类型的对象进行交互,而不必暴露它们的私有成员。


推荐阅读