头文件中的struct无法识别

Bbv*_*ghe 0 c++ struct header-files

practice.h

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

};
Run Code Online (Sandbox Code Playgroud)

practice.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;
}
Run Code Online (Sandbox Code Playgroud)

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

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'
Run Code Online (Sandbox Code Playgroud)

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

use*_*019 5

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

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

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

};
Run Code Online (Sandbox Code Playgroud)

这不会像你一样显示在cpp文件中 using namespace std;

您可以将使用行放在#include"practice.h"之前,但这被认为是错误的样式,因为标题现在不是自包含的,您可能会遇到名称空间冲突.