C ++ 11:私有成员安全 [英] C++11: Private member security

查看:135
本文介绍了C ++ 11:私有成员安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑下一个代码:

Let's consider the next code:

#include <iostream>
#include "mydemangled.hpp"

using namespace std;

struct A
{
private:
    struct B {
       int get() const { return 5; }
    };

public:
   B get() const { return B(); }
};

int main()
{
    A a;
    A::B b = a.get();

    cout << demangled(b) << endl;
    cout << b.get() << endl;
}

编译器(gcc 4.7.2) c> A :: B 是私有的。好吧。
所以,我改变代码:

And the compiler (gcc 4.7.2) yells saying that A::B is private. All right. So, I change the code:

int main()
{
   A a;

   cout << demangled(a.get()) << endl;
   cout << a.get().get() << endl;
}

且不会叫喊:

$ ./a.out
A::B
5

意思是,我不能创建 A :: B 的实例,但我可以使用它。
所以,新的更改(我的问题的关键)。

Meaning, I can't to create instances of A::B, but I can use it. So, new change (the key of my question).

int main()
{
   A a;
   auto b = a.get();

   cout << demangled(b) << endl;
   cout << b.get() << endl;
}

并输出:

$ ./a.out
A::B
5

这里有什么麻烦, A :: B private(因此它的构造函数,复制构造函数等等)?

What is the trouble here, being A::B private (and thus its constructors, copy constructors and so on)?

推荐答案

通常,访问控制名称或符号,不是
基础实体。有,并且总是,许多
访问私人成员的方法;你不能做的是使用这样的成员的
名称。

In general, access controls names or symbols, not the underlying entities. There are, and always have been, numerous ways of accessing private members; what you cannot do is use the name of such a member.

在你的例子中,你不使用名称,所以没有
问题。

In your examples, you don't use the name, so there is no problem.

这篇关于C ++ 11:私有成员安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆