Difference between “::” “.” and “->” in c++

2019-09-22 06:10发布

问题:

I have found the class Kwadrat. The author used three types of operator ::, . and ->. The arrow is the one that only works. What's the difference between those three?

#include <iostream>

using namespace std;

class Kwadrat{
public:
int val1, val2, val3;
    Kwadrat(int val1, int val2, int val3)
    {
        this->val1 = val1;
        //this.val2 = val2;
        //this::val3 = val3;
    }
};

int main()
{
    Kwadrat* kwadrat = new Kwadrat(1,2,3);
    cout<<kwadrat->val1<<endl;
    cout<<kwadrat->val2<<endl;
    cout<<kwadrat->val3<<endl;
    return 0;
}

回答1:

  • :: names a type within a namespace, a variable within a namespace, a static variable in a class, or a type in a class.
  • . names an instance variable or member function
  • a->b is syntactic sugar for (*a).b.


回答2:

-> works on pointers, . on objects and :: on namespaces. Specifically:

  1. Use -> or . when accessing a class/struct/union member, in the first case through a pointer, in the latter through a reference.
  2. Use :: to reference the function inside a namespace or a class (namespaces), for instance, when defining methods declared with the class.


回答3:

x->y is equivalent to (*x).y. That is, -> dereferences the variable before getting the field while the dot operator just gets the field.

x::y looks up y in namespace x.



回答4:

The use cases are:

  1. -> is used when you have a pointer
  2. . is used when you have an object instance
  3. :: is used when you have a static member or a namespace


回答5:

The -> is the equivalent of saying (*Kwadrat_pointer).value. You use it when you have an object pointer calling object methods or retrieving object members.

The . operator is used to access the methods and members in the object that is calling it (that is, the object on the left side of the ".").

The :: operator is called the scope operator. It tells your program where to look, for example when defining a class method outside of the class declaration.