has initializer but incomplete type (stuct c++)

huangapple go评论97阅读模式
英文:

has initializer but incomplete type (stuct c++)

问题

I don't understand what's going on

#ifndef __UTIL__
    #define __UTIL__

    struct Contact;
    using Contact = struct Contact;
#endif
#include "util.hpp"
#include <iostream>

struct Contact
{
    std::string fistname;
    std::string lastname;
    int age;
    std::string number;
};
#include "util.hpp"
#include <iostream>

int main()
{
    Contact newContact{"Cage", "Jhonny", 20, "+33225254554"};
    return 0;
}

Compilation result:
has initializer but incomplete type (stuct c++)

I don't understand why there is this error. But everything seems correct.

英文:

I don't understand what's going on

Util.hpp>>>>>>>>>>

#ifndef __UTIL__
    #define __UTIL__

    struct Contact;
    using Contact = struct Contact;
#endif

Util.cpp>>>>>>>>>

#include &quot;util.hpp&quot;
#include &lt;iostream&gt;

struct Contact
{
    std::string fistname;
    std::string lastname;
    int age;
    std::string number;
};

main.cpp>>>>>>>>>>>

#include &quot;util.hpp&quot;
#include &lt;iostream&gt;


int main()
{
    Contact newContact{&quot;Cage&quot;, &quot;Jhonny&quot;, 20 ,&quot;+33225254554&quot;};
    return 0;
}

compilation result >>>>>>>>>>>>

has initializer but incomplete type (stuct c++)

I don't understand why there is this error. But everything seems correct

答案1

得分: 2

你必须将整个struct定义放在你的util.hpp文件中。你现在只有对在main.cpp看来从未被完整解释的某事的前向声明。

在编译器术语中,这是一种“不完整类型”。

英文:

You must put your entire struct definition in your util.hpp file. All you have now is a forward declaration to something that as far as main.cpp is concerned, is never fully explained.

In compiler terms, this is an "incomplete type".

答案2

得分: 0

Contactmain.cpp中是一个不完整的类型。

util.hpp中像struct Contact这样的声明被称为前向声明:你基本上告诉编译器将来会定义一个名为Contact的结构体。只有前向声明,你只能声明指向Contact的指针和/或引用,因为编译器不需要知道它的大小来处理指针和引用。

但是要在main.cpp中实际声明一个类型为Contact的变量,编译器需要一个完整的类型,而不仅仅是将来会存在的东西的名称 —— 它需要知道它是什么。通常情况下,你会在util.hpp中完全声明结构体,除非你有充分的理由不这样做。

英文:

Contact is an incomplete type in main.cpp.

A declaration like struct Contact in util.hpp is called a forward declaration: you are basically telling the compiler that a struct called Contact will eventually be defined. With just the forward declaration, you can only declare pointers and/or references to Contact, since the compiler does not need to know its size for pointers and references.

But to actually declare a variable of type Contact, in your main.cpp, the compiler needs a complete type, not just the name of something that will eventually exist -- it needs to know what it is. Typically you would fully declare the struct in Util.hpp unless you have a good reason not to.

huangapple
  • 本文由 发表于 2023年6月9日 08:42:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定