c++ - 使用自动与显式指定私有(private)结构类型时的行为差异

标签 c++ c++11 type-deduction

<分区>

考虑以下代码片段

class BST
{
    struct Node
    {
        int data_;
        Node * left_, * right;
    } * root_ = nullptr;

    public:

    Node * getRoot()
    {
        return root_;
    }
};

int main() {
    BST bst;
    auto root1 = bst.getRoot();          // Compiles fine
    BST::Node * root2 = bst.getRoot();   // Gives error
}

当获取值并分配给使用 auto 推导其类型的变量时,代码可以正常编译。当明确指定类型时,它会失败。为什么会有这种行为差异?我预计两者都会失败。

最佳答案

问题是 struct BST::Nodeclass BST 中是私有(private)的。请记住, 默认为所有 成员私有(private)访问,而不仅仅是实例成员和函数。

使用 auto 很好,因为您从未明确提及私有(private)类型。

关于c++ - 使用自动与显式指定私有(private)结构类型时的行为差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37383772/

相关文章:

c++ - 如何找到auto_ptr的地址

c++ - 如何在 C++ 中创建自定义整数序列

C++11 堆栈变量的线程安全

c++ - 为 std::future 删除

c++ - 将参数转发给模板成员函数

c++ - 我们什么时候可以省略 C++11 lambda 中的返回类型?

c++ - 获取模板类的类型

c++ - 海军作战任务,无法使用setw()分配数组,您能帮我吗?

C++:覆盖新创建的数组中的元素

c++ - dup 不重定向