What does the :: mean in C++? [duplicate]
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
meansB
is an identifier within eithernamespace
orclass
typeA
,A.B
meansB
is a member of thestruct
,class
, orunion
type an instance of which is referred to by the object or referenceA
, andA->B
meansB
is a member of thestruct
,class
, orunion
type an instance of which is referred to by the pointerA
. (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.
}
精彩评论