class student{ public: int hours; void vs(int l){ hours += l*hours; } } student st1,st2; //в чем различие (1) и (2)? //(1) st1.hours=10 st1.vs(5); //(2) st2::hours=20; st2::vs(3); 
  • Tell me, does the second option work at all? In general, :: is a scope operator. It is possible that the developers have added such an opportunity to access the members of the class, or using this operator in this form does not contradict the logic of its work. But in any case, the point is the operator of access to the class member / method, and for this purpose it is worth using it. The code will be clearer. - MaxXx1313

3 answers 3

:: separates the class name from the name of the type or member defined in it (a variable, function or constant). In this case, the class name acts as a namespace.

. separates the name of an object (that is, an instance of a class) from the name of a member: variable, function, or constant.

In your example, the second option is wrong, because You are trying to use the object name where the class name should be used.

  • As for :: - I do not agree. There are counter-examples. 1. Calling a non-static function from the base class. 2. Definition of non-inline member functions of a class. - gecube
  • In general, I agree. When dealing with a class, use ::. When with the object - a point. - skegg 4:16
  • Yes, in this respect the "+". Also add that in this key class = structure - gecube
  • @gecube, author code with st2 :: is not compiled in any case. (even if you omit the missing ';' ) - avp
  • @avp, I agree. For this we need additional. conditions - gecube

The difference between what

. - operator selector member-class (structure).

We use it like this:

  struct x {int y;} ... x my_x, *my_p_x; ... my_x.y = 10; (*my_p_x).y = 2; // эквивалентно my_p_x->y = 2, если оператор -> не перегружен 

:: - namespace selection operator. With this class , the struct creates its own namespace.

  namespace x {int y;} struct x {int y;} // ERROR! пространство имен x уже определено ... x::y = 10; ... int k; void func () { int k; k = 10; // локальная переменная ::k = 2; // присваиваем 2 переменной глобальной } 

Both operators can not be overloaded !!!

    You probably write on the pros? In this case, the operator "." (dot) is the access operator for the members of the class (structure) A "::" (double colon) is the scope resolution operator. That is, the first statement can be applied to instances, and the second to types and namespaces. In your example, the strings after // (2) are incorrect - you are trying to access its methods from an instance of a class. To make this code correct, you need to write the following:

    student :: vs (3);

    but now it is still incorrect, because here an attempt is made to refer to the non-static method vs (). For the code to be correct, you need to declare vs static (and not use the reference to the non-static field of hours in its body)