Why is this code compiling?

What are the exact rules for determining access rights for objects nested in private sections of other objects?

For example, in the code below, the structure is proxy_tnested in a private section abc_t, and yet its methods are available for the function main. Why does it even compile?

#include <iostream>
#include <valarray>

using namespace std;

class abc_t{
  private: 
    struct proxy_t{
      proxy_t operator()(double& a, double& b){ __a=a; __b=b; return *this; }
      double a(){ return __a; }
      double b(){ return __b; }
      private:
        double __a, __b;
    };

  public:
    abc_t( const size_t N ){ 
       _a.resize(N,-101.); 
       _b.resize(N,-202.);  
    }
    double a(size_t j){ return _a[j]; }
    double b(size_t j){ return _b[j]; }

    proxy_t operator[](const size_t j) { return _proxy(_a[j],_b[j]); }

  private:
    valarray<double> _a;
    valarray<double> _b;
    proxy_t _proxy;
};


int main(){
 size_t n_elem=10;
 abc_t abc(n_elem);
 cout<<"direct: "<< abc.a(1)<<"  "<<abc.b(1)<<"\n";
 cout<<"proxied:"<<abc[1].a()<<"  "<<abc[1].b()<<"\n";  // ain't proxy_t::aa() private?
 //cout<<abc[1]; // doomed to fail
}
+5
source share
4 answers

This line is important, which I will talk about:

cout<<"proxied:"<<abc[1].a()<<"  "<<abc[1].b()<<"\n";

When you call abc [1], this is the public abc_t method. It's really.

It returns proxy_t. Although the declaration of this class (proxy_t) is not defined, you are not actually using this return variable to create a new object. If you did the following, this would not compile.

proxy_t p = abc[1];

, proxy_t, , . - , ( ).

proxy_t , , - , abc_t. , , - / / , .

. ( ). . , proxy_t:: a() , CAN , main proxy_t.

+5

struct proxy_t private, , , . , proxy_t- , abc_t, .

, -, ++, , .

+1

abc [1].a(), :

proxy_t operator[](const size_t j) { return _proxy(_a[j],_b[j]); }

1 j.

_proxy(_a[j],_b[j]) 

, a()

0

proxy_t abc_t, , abc_t, (.. ). , proxy_t, , .

( ), (11.8):

, . ; (. 11) .

Reading between the lines: since the nested class is a “simple” member, normal access control is applied when someone refers to this type (i.e. returns proxy_t). But proxy_tspecial access rules are not applied for access to members - if you managed to get an object proxy_tfrom a privileged source, you can access its members as if it were not a nested class.

0
source

All Articles