加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在自由函数中定义的类型,可通过自动外部访问.语言错误或功

发布时间:2020-12-16 10:00:06 所属栏目:百科 来源:网络整理
导读:让我们在自由函数中定义一个类,并在外部访问它: #include iostreamauto myFunc(){ class MyType{public: int i = 0; int j = 1;}; return MyType();}int main() { auto my_type = myFunc(); std::cout my_type.i " " my_type.j "n"; return 0;} 它编译,按
让我们在自由函数中定义一个类,并在外部访问它:

#include <iostream>
auto myFunc(){
    class MyType{public: int i = 0; int j = 1;};
    return MyType();
}
int main() {
    auto my_type = myFunc();
    std::cout << my_type.i << " " << my_type.j << "n";
    return 0;
}

它编译,按预期运行:

0 1

名称MyType已正确隐藏:
如果我们替换auto,以下将无法编译:

int main() {
    MyType my_type = myFunc();
    std::cout << my_type.i << " " << my_type.j << "n";
    return 0;
}

标准对此有何评价?

怎么预防呢?以下代码没有帮助:

namespace{
auto myFunc(){
    class MyType{public: int i = 0; int j = 1;};
    return MyType();
}
}
int main() {
    auto my_type = myFunc();
    std::cout << my_type.i << " " << my_type.j << "n";
    // your code goes here
    return 0;
}

解决方法

标准没有具体说明这一点,除了 – 正如你已经指出的那样 – 它是具有范围的名称,而不是类型.使用auto会绕过类型的名称,无论名称的范围如何,都可以使用这种方法获取类型.

它有点类似于making a nested class private doesn’t mean you can’t use instances of it,only that you can’t name it outside of the encapsulating class’s scope.

我不知道你是如何“阻止”它,也不是你想要的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读