programing tip

"::" "."의 차이점은 무엇입니까?

itbloger 2020. 10. 18. 08:38
반응형

"::" "."의 차이점은 무엇입니까? C ++의 "->"


중복 가능성 :
C ++에서 클래스 멤버를 참조하기 위해 점, 화살표 또는 이중 콜론을 언제 사용합니까?

Kwadrat라는 클래스를 만들었고 내부에 세 개의 int 필드가 있습니다. 코드 블록은 ::, .및으로 객체의 필드에 들어갈 수 있다는 조언을 제공합니다 ->. 화살표는 작동 만하는 것이지만, 그 이유는 무엇입니까? 이 세 가지의 차이점은 무엇입니까?

#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. ->통해 대상 부재 변수 및 방법 액세스 pointer개체

Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();

2. .개체를 통해 개체 멤버 변수 및 메서드에 액세스instance

Foo foo;
foo.member_var = 10;
foo.member_func();

3. 또는 ::의 정적 변수 및 메서드에 액세스 합니다. 또한 다른 범위에서 변수와 함수에 액세스하는 데 사용할 수도 있습니다 (실제로 클래스, 구조체, 네임 스페이스는이 경우 범위입니다).class/structnamespace

int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();

C ++에서는 유형에 따라 다른 연산자를 사용하여 필드 또는 메서드에 액세스 할 수 있습니다.

  • ClassName :: FieldName : 클래스 공용 정적 필드 및 메서드
  • ClassInstance.FieldName : 클래스 참조를 통해 공용 필드 (또는 메서드)에 액세스
  • ClassPointer-> FieldName : 클래스 포인터를 역 참조하는 공용 필드 (또는 메서드)에 액세스

::는 클래스 인스턴스가 아닌 클래스 이름과 함께 사용해야합니다. 정적 필드 또는 메서드는 클래스의 모든 인스턴스에 공통이기 때문입니다.

class AClass{
public:
static int static_field;
int instance_field;

static void static_method();
void method();
};

다음 방법으로 액세스합니다.

AClass instance;
AClass *pointer = new AClass();

instance.instance_field; //access instance_field through a reference to AClass
instance.method();

pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();

AClass::static_field;  
AClass::static_method();

매우 간단하게 ::말하면 범위 지정 연산자, .액세스 연산자 (실제 이름이 무엇인지 잊었습니까?), ->역 참조 화살표입니다.

::-함수의 범위를 지정합니다. 즉, 컴파일러는 함수가 어떤 클래스에 있는지, 따라서 호출 방법을 알 수 있습니다. 이 연산자를 사용하여 함수를 호출하는 경우 함수는 static함수입니다.

.-이미 생성 된 객체의 멤버 함수에 액세스 할 수 있습니다. 예를 들어, 유형이있는 인스턴스화 된 객체 Foo x; x.bar()에서 메서드 bar()호출합니다 . 이것을 사용하여 공용 클래스 변수에 액세스 할 수도 있습니다.xFoo

->- .포인터 유형에서 작동한다는 점을 제외하면 본질적으로 동일 합니다. 본질적으로를 호출하는 것보다 포인터를 역 참조합니다 .. 이것을 사용하는 것은(*ptr).method()


개체에 대한 포인터가 있습니다. 따라서 포인터가 가리키는 개체의 필드에 액세스해야합니다. 사용하는 포인터를 역 참조하고 *필드에 액세스하려면을 사용 .하므로 다음을 사용할 수 있습니다.

cout << (*kwadrat).val1;

괄호가 필요합니다. 이 작업은 오래 전에 (C가 어렸을 때) "속기"방법을 만들기로 결정했을만큼 일반적입니다.

cout << kwadrat->val1;

이들은 동일하게 정의됩니다. 보시다시피 ->기본적으로 a *와 a .를 단일 작업으로 결합 합니다. 객체 또는 객체에 대한 참조를 직접 처리 .하는 경우 먼저 포인터를 역 참조하지 않고 를 사용할 수 있습니다 .

Kwadrat kwadrat2(2,3,4);

cout << kwadrat2.val1;

The :: is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:

struct something { 
    static int x; // this only declares `something::x`. Often found in a header
};

int something::x;  // this defines `something::x`. Usually in .cpp/.cc/.C file.

In this case, since x is static, it's not associated with any particular instance of something. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:

something::x = 10;

std::cout << something::x;

Note, however, that it's also permitted to access a static member as if it was a member of a particular object:

something s;

s.x = 1;

At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.


The three operators have related but different meanings, despite the misleading note from the IDE.

The :: operator is known as the scope resolution operator, and it is used to get from a namespace or class to one of its members.

The . and -> operators are for accessing an object instance's members, and only comes into play after creating an object instance. You use . if you have an actual object (or a reference to the object, declared with & in the declared type), and you use -> if you have a pointer to an object (declared with * in the declared type).

The this object is always a pointer to the current instance, hence why the -> operator is the only one that works.

Examples:

// In a header file
namespace Namespace {
    class Class {
        private:
            int x;
        public:
            Class() : x(4) {}
            void incrementX();
    };
}

// In an implementation file
namespace Namespace {
    void Class::incrementX() {    // Using scope resolution to get to the class member when we aren't using an instance
        ++(this->x);              // this is a pointer, so using ->. Equivalent to ++((*this).x)
    }
}

// In a separate file lies your main method
int main() {
    Namespace::Class myInstance;   // instantiates an instance. Note the scope resolution
    Namespace::Class *myPointer = new Namespace::Class;
    myInstance.incrementX();       // Calling a function on an object instance.
    myPointer->incrementX();       // Calling a function on an object pointer.
    (*myPointer).incrementX();     // Calling a function on an object pointer by dereferencing first

    return 0;
}

The '::' is for static members.


-> is for pointers to a class instance

. is for class instances

:: is for classnames - for example when using a static member


Others have answered the different syntaxes, but please note, when you are doing your couts, you are only using ->:

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

참고URL : https://stackoverflow.com/questions/11902791/what-is-the-difference-between-and-in-c

반응형

'programing tip' 카테고리의 다른 글

XmlDocument를 사용하여 XML 속성 읽기  (0) 2020.10.18
Razor로 인코딩 된 HTML 표시  (0) 2020.10.18
빛나는 앱에서 만든 플롯 저장  (0) 2020.10.17
식의 차이  (0) 2020.10.17
하위 도메인에서 localStorage 사용  (0) 2020.10.17