简体   繁体   中英

Understanding non-static class member access

I'd like to understand all case allowing us using of the :: operator to get access class data members. For instance, we could use :: to access static data members. Actually,

#include <iostream>

struct A
{
    static const int b = 3;
};

int main() { std::cout << A::b << std::endl; }

also, we could use the expression to get access to non-static data members within a brace-or-equal initializer of a non-static data member.

#include <iostream>

struct A
{
    int b = 3;
    void foo()
    {
        std::cout << A::b << std::endl;
    }
};

int main() { A().foo(); }

DEMO

I'm looking for the rule covering all cases where we could use :: operator. What chapter of the Strandard tells us that we should't use :: to accessing non-static data member like this

#include <iostream>

struct A
{
    int b = 3;
};

int main() { std::cout << A::b << std:endl; } //error

5.1.1.13 in the C++14 standard:

An id-expression that denotes a non-static data member or non-static member function of a class can only be used:

  • as part of a class member access (5.2.5) in which the object expression refers to the member's class or a class derived from that class, or
  • to form a pointer to member (5.3.1), or
  • if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

Case 1 is where you are trying to be more specific about what member you mean. For example aA::b .

Case 2 is where you take the address of the member. For example &A::b .

Case 3 is where it is unevaluated. For example sizeof(A::b) .

The A::b in your example is none of these, so it is illegal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM