在一次测试中,我不得不在 struct car 中编写一些参数(汽车的一些特征)。我写了这段代码:
struct car
{
string plate, template, brand;
int doors;
float engine_size;
void ins()
{
cout << "Insert the template" << endl;
cin >> template;
cout << "Insert the engine size" << endl;
cin >> engine_size;
// it would continue but it is the same
}
}
我的教授告诉我这是错误的,他用这段代码更正了它:
struct car
{
string plate, template, brand;
int doors;
float engine_size;
void ins()
{
string t;
int e;
cout << "Insert the template" << endl;
cin >> t;
t = template;
cout << "Insert the engine size" << endl;
cin >> e;
e = engine_size
// it would continue but it is the same
}
}
最佳答案
也许您的教授对 operator>>
的工作原理有一些奇怪的误解。这是我能想到的唯一解释。但是,我认为这些“修复”没有任何充分的理由。相反,您不需要那些额外的变量,它们只会让代码更冗长而没有任何好处。请注意,即使您需要这些额外的变量,您也应该只在需要时而不是在函数的顶部声明它们。
您的代码中存在两个真正的问题:您在类声明后遗漏了一个 ;
并且您不能将 template
用作变量名。
其实我觉得一定是哪里有什么误会。你确定你理解你的教授提出的建议并正确地张贴在这里吗?我建议您再次询问他们,解释为什么要进行这些更改。无论如何,如果你的老师在没有给出充分理由的情况下告诉你“那样做”,那么这就是一个糟糕的老师。不要遵守你不理解的规则。
PS:最后也是最不重要的一点,我忽略了一个事实,即你的分配方式是错误的。你的第二个片段真的非常正确......
关于c++ - 这两种结构的写法是一样的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55899779/