开发者

What does the :: mean in C++? [duplicate]

This question already has answers here: When do I use a dot, arrow, or double colon to refer to members of a class in C++? (4 answers) Closed 6 years ago. 开发者_如何学JAVA
void weight_data::rev_seq(string &seq){ 
//TODO
std::reverse(seq.begin(), seq.end());
}

In this C++ method, I think this method does not return anything, so the prefix is void, what does :: tell the relationships between weight_data and rev_seq(string &seq)? Thanks!


void is the return type. :: is the scope resolution operator, so it means rev_seq is inside the scope of weight_data. weight_data could be either a namespace or a class (based on what you've given, it's not possible to say which).


In C++,

  • A::B means B is an identifier within either namespace or class type A,
  • A.B means B is a member of the struct, class, or union type an instance of which is referred to by the object or reference A, and
  • A->B means B is a member of the struct, class, or union type an instance of which is referred to by the pointer A. (It's equivalent to (*A).B.)

In some other languages, all three cases are covered by a . only.

Note that in C++, member function don't have to be implemented (defined) within their class' definition. (If they are, they are implicitly inline.) They can be, and often are, implemented in separate implementation (.cpp) files. This has the advantage that not all users of a class need to recompile when you change an implementation of one of the class' member functions. So unless weight_data is a namespace name, void weight_data::rev_seq(string &seq) {...} is such a definition of a class member outside of its class.


weight_data is a namespace or class name.


The line void weight_data::rev_seq(string &seq) tells the compiler that this is the definition of the rev_seq(string &seq) member function from the weight_data. If this just said void rev_seq(string &seq) { ... } the compiler would think that a non-member function was being defined, as opposed to the rev_seq(string &seq) member function of the weight_data class.

class weight_data
{
    void rev_str(string &seq);
}

It can also mean that rev_str refers to a function that is part of namespace weight_data.

namespace weight_data
{
    void rev_str(string &seq);
}


Just thought of adding 2 more interesting things about the ::

a) Operator :: is both a unary and a binary operator

struct A{
   int m;
};

int x;
int main(){
   ::x;                     // Unary
   int (A::*p) = &A::m;     // Binary
}

b) $10.3/12 - "Explicit qualification with the scope operator (5.1) suppresses the virtual call mechanism."

struct A{
   virtual void f(){cout << 1;}
};

struct B : A{
   void f(){cout << 2;}
};

int x;
int main(){
   B b;
   A &ra = b;
   ra.f();     // dynamic binding, prints 2
   ra.A::f();  // suppress VF mechanism, prints 1.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜