practice.h구조체
struct CandyBar
{
string name;
double weight;
int calories;
};
는
#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.cpp :
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'
원인이 무엇인가 모든 오류 중? 변수가 구조체의 필드로 인식되지 않는 이유는 무엇입니까?
헤더에'#include'과'std ::'가'string name;'앞에 누락되었습니다. 편집 : 소스 파일에 헤더를 포함하기 전에''을 포함하고 있다는 것을 알지 못 했으므로 include 문 없이도 작동해야하지만 의존성이 있으므로 헤더에 include 문을 추가하는 것이 좋습니다. std :: string에. 그리고'namespace std;를 사용하는 것은 매우 나쁜 습관입니다! –
Praetorian
적어도 "using namespace std;"는 헤더가 아닌 * .cpp 파일에 있습니다. – aschepler