programing

C++의 "X does not name a type" 오류

instargram 2023. 4. 17. 21:17
반응형

C++의 "X does not name a type" 오류

다음과 같이 선언된 클래스가 2개 있습니다.

class User
{
public:
  MyMessageBox dataMsgBox;
};

class MyMessageBox
{
public:
  void sendMessage(Message *msg, User *recvr);
  Message receiveMessage();
  vector<Message> *dataMessageList;
};

gcc를 사용하여 컴파일을 시도하면 다음 오류가 나타납니다.

MyMessageBox가 유형을 지정하지 않음

를 할 때User 해서 '이렇게 하다'로 됩니다.MyMessageBox ,,MyMessageBox아직 정의되지 않았습니다..MyMessageBox존재하기 때문에 클래스 멤버의 의미를 이해할 수 없습니다.

하셔야 합니다.MyMessageBox멤버로 사용하기 전에 정의되어 있습니다.이는 정의 순서를 반대로 함으로써 해결됩니다.단, 주기적인 의존관계가 있습니다.이동하는 경우MyMessageBox 이상User과 같습니다.MyMessageBox이 name라는 User정의되지 않습니다!

당신이 할 수 있는 것은 전방 신고입니다. User즉, 선언은 하지만 정의하지는 않습니다.컴파일 중에 선언되었지만 정의되지 않은 유형을 불완전 유형이라고 합니다.보다 간단한 예를 들어 보겠습니다.

struct foo; // foo is *declared* to be a struct, but that struct is not yet defined

struct bar
{
    // this is okay, it's just a pointer;
    // we can point to something without knowing how that something is defined
    foo* fp; 

    // likewise, we can form a reference to it
    void some_func(foo& fr);

    // but this would be an error, as before, because it requires a definition
    /* foo fooMember; */
};

struct foo // okay, now define foo!
{
    int fooInt;
    double fooDouble;
};

void bar::some_func(foo& fr)
{
    // now that foo is defined, we can read that reference:
    fr.fooInt = 111605;
    fr.foDouble = 123.456;
}

선언에 User,MyMessageBox할 수 .

class User; // let the compiler know such a class will be defined

class MyMessageBox
{
public:
    // this is ok, no definitions needed yet for User (or Message)
    void sendMessage(Message *msg, User *recvr); 

    Message receiveMessage();
    vector<Message>* dataMessageList;
};

class User
{
public:
    // also ok, since it's now defined
    MyMessageBox dataMsgBox;
};

이 작업은 다른 방법으로 수행할 수 없습니다. 앞서 설명한 바와 같이 클래스 구성원은 정의를 가지고 있어야 합니다.(이유는 컴파일러가 메모리 용량을 알아야 하기 때문입니다.User멤버의 사이즈를 알아야 합니다.)면약당당면면면면면면:

class MyMessageBox;

class User
{
public:
    // size not available! it's an incomplete type
    MyMessageBox dataMsgBox;
};

아직 사이즈를 모르기 때문에 안 될 것 같아요.


참고로 이 기능은 다음과 같습니다.

 void sendMessage(Message *msg, User *recvr);

둘 다 포인터로 찍으면 안 될 것 같아요메시지 없이 메시지를 발송할 수 없으며 발송할 사용자 없이 메시지를 발송할 수도 없습니다.두 상황 모두 null을 어느 파라미터에 인수로 전달함으로써 표현할 수 있습니다(null은 완전히 유효한 포인터 값입니다).

대신 참조를 사용합니다(가능한 한 계속).

 void sendMessage(const Message& msg, User& recvr);
  1. 사용자 전달 선언
  2. My Message Box 선언을 사용자 앞에 배치합니다.

C++는 C++는 C++는 C++를 사용합니다.사용하는 각 클래스가 먼저 정의되어 있어야 합니다.은 you 다 you you youMyMessageBox정의하기 전에.이 경우 2개의 클래스 정의를 간단하게 교환할 수 있습니다.

MyMessageBox를 사용자 앞에 정의해야 합니다.사용자는 MyMessageBox의 오브젝트를 값별로 포함하므로 컴파일러는 그 크기를 알아야 합니다.

또한 My Message Box에는 User* 유형의 멤버가 포함되어 있기 때문에 My Message Box에 대해 User be for My Message Box를 선언해야 합니다.

이와 관련하여 다음과 같은 경우:

    class User; // let the compiler know such a class will be defined

    class MyMessageBox
    {
    public:
        User* myUser;
    };

    class User
    {
    public:
        // also ok, since it's now defined
        MyMessageBox dataMsgBox;
    };

그러면 사용자가 My Message Box에서 포인터로 정의되어 있기 때문에 이 방법도 작동합니다.

제 경우, 이 매우 유익한 오류는 순환 의존성에 의해 발생된 것으로 드러났습니다.대신

// A.hpp
#include "B.hpp"

class A {
    B b;
}

// B.hpp
#include "A.hpp"

class B {
    A a;
}

두 번째 파일을 로 변경했습니다.

// B.hpp
class A;

class B {
    A a;
}

모든 컴파일러 오류와 IDE에서 구문 강조 표시가 갑자기 없어졌습니다.

난 나중에 이걸 넣어야 했어#include "A.hpp"맨 위에B.cpp이 경우 순환 의존성이 없기 때문에 괜찮습니다.B.cpp -> A.hpp -> B.hpp -> /).

프로토타입을 사용하려면 먼저 프로토타입을 선언해야 합니다.

class User;

class MyMessageBox
{
public:
 void sendMessage(Message *msg, User *recvr);
 Message receiveMessage();
 vector<Message> *dataMessageList;
};

class User
{
public:
 MyMessageBox dataMsgBox;
};

edit: 타입을 스왑.

C++에서는 헤더 파일마다 1개의 클래스가 있는 것이 항상 권장됩니다.이 설명은 SO [1]를 참조하십시오.GManNickG의 답변은 왜 이런 일이 일어나는지 말해준다.하지만 이 문제를 해결하는 가장 좋은 방법은Userclass in header file (1개의 헤더 파일)User.h)와MyMessageBox다른 헤더 파일 내의 클래스)MyMessageBox.h) 。다음으로,User.h다음을 포함합니다.MyMessageBox.h및 인MyMessageBox.h다음을 포함합니다.User.h코드 컴파일이 성공하려면 , 「include gauds」[2]를 잊지 말아 주세요.

언급URL : https://stackoverflow.com/questions/2133250/x-does-not-name-a-type-error-in-c

반응형