practice.h
struct CandyBar
{
string name;
double weight;
int calories;
};
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;
}
when I build the solution, I get the errors:
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'
what is cause of all the errors? why won't the variables get recognized as fields of the struct?
#include <string>andstd::beforestring name;in the header. Edit: Didn't notice that you're including<string>before including the header in your source file, so it should work without the include statement too, but it's still good practice to add the include statement in the header since it does depend onstd::string. Andusing namespace std;is very bad practice!using namespace std;was in a *.cpp file and not in a header.