无法识别头文件中的结构
struct in header file not recognized
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 – 头文件 库兰马克
相关文章:
- C++将文本文件中的数据读取到结构数组中
- 调用 C 文件中的"C++"结构
- 结构包含在两个头文件中,这两个文件我都不拥有
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 介子复制/安装头文件到输出目录并保持文件夹结构
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 将内部带有矢量的结构保存/读取到二进制文件中
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 将文本文件解析为树状数据结构
- 如何使用位字段将数据从二进制文件复制到结构中?
- 在树结构.txt文件中搜索节点
- 当结构位于单独的头文件中时'unregistered datatype'在 QML 中出现Q_GADGET错误
- 将文件读入数据结构
- 如何读取没有数组或结构的 3 列文件
- (ODR 使用问题)在不同文件中priority_queue名称相同的结构
- 在.cpp文件之间传递结构声明,而不使用全局头文件
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 如何在结构/文件中搜索名称