英文:
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:
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 "util.hpp"
#include <iostream>
struct Contact
{
std::string fistname;
std::string lastname;
int age;
std::string number;
};
main.cpp>>>>>>>>>>>
#include "util.hpp"
#include <iostream>
int main()
{
Contact newContact{"Cage", "Jhonny", 20 ,"+33225254554"};
return 0;
}
compilation result >>>>>>>>>>>>
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
Contact
在main.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论