无法识别头文件中的结构

struct in header file not recognized

本文关键字:结构 文件 识别      更新时间:2023-10-16

practice.h

struct CandyBar
{
    string name;
    double weight;
    int calories;
};

练习.cpp

#include    <iostream>
#include    <string>
#include    "practice.h"  
using namespace std;
int main()
{
    CandyBar snacks{ "Mocha Munch", 2.3, 350 };
    cout << snacks.name << "t" << snacks.weight << "t" << snacks.calories << endl;
    return 0;
}

当我构建解决方案时,我收到错误:

practice.h(5): error C2146: syntax error : missing ';' before identifier 'name'
practice.h(5): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2440: 'initializing' : cannot convert from 'const char [12]' to 'double'
There is no context in which this conversion is possible
practice.cpp(20): warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data
practice.cpp(20): error C2078: too many initializers
practice.cpp(22): error C2039: 'name' : is not a member of 'CandyBar'
practice.h(4) : see declaration of 'CandyBar'

所有错误的原因是什么? 为什么变量不会被识别为结构的字段?

问题是当标头解析器没有类型字符串时。

最好的方法是包含命名空间,例如

struct CandyBar
{
    std::string name;
    double weight;
    int calories;
};

这不会显示在 cpp 文件中,因为您已经using namespace std;

您可以将 using 行放在 #include"practice.h"之前,但这被认为是不好的样式,因为标头现在不是独立的,并且可能会出现命名空间冲突。

你需要包括在实践中。

这样:

#include <string>
struct CandyBar
{
   std::string name;  // And also std:: before string, as Praetorian pointed out  
   double weight;
   int calories;
};

包含不是必需的,但您必须导入命名空间std或完全限定其用法。因此,要么重复using语句,要么将name声明为类型 std::string

你应该使用"#ifndef"、"#define"。因为也许头文件可以调用初始化几次。因此,您犯了错误。看看这个: C++'ta 分离编译 II – 头文件 库兰马克