gpt4 book ai didi

c++ - 我无法弄清楚 C++ 语法错误 "expected ` ;' before ‘{’ token ”

转载 作者:太空狗 更新时间:2023-10-29 19:52:34 29 4
gpt4 key购买 nike

我有这个简单的代码,但出现语法错误:

file.cc:67: error: expected `;' before ‘{’ token
file.cc:73: error: expected primary-expression before ‘(’ token
file.cc:73: error: expected primary-expression before ‘n’
file.cc:73: error: expected `;' before ‘{’ token

我在第 67 行和第 73 行周围标上了星号,它们是类的构造函数。我是 C++ 的新手,找不到语法问题。这是我第一次制作构造函数。

int main() {

class Patient {
private: // default is private but stating explicitly here for learning purposes
std::string name; //object
int height; //object
int weight; //object
public:
Patient(); //constructor
Patient(std::string); //constructor

void set_name (std::string n) {name=n;} //fn
void set_height (int h) {if (height>0){height=h;} else {height=0;}} //fn
void set_weight (int w) {if (weight>0){weight=w;} else {weight=0;}} //fn

std::string get_name(){return name;} //fn
int get_height(){return height;} //fn
int get_weight(){return weight;} //fn

int bmi(void) {
if ((height!=0) && (weight!=0))
return (weight/(height*height));
else
return 0;
}
};

Patient::Patient () { // **LINE 67**
name="string";
height=0,
weight=0;
}

Patient::Patient(std::string n) {name=n;height=0;weight=0;} // **LINE 73**

Patient father("Andrew Nonymous");
Patient mother("Ursula N. Known");
Patient baby;

//Father's height and weight are unknown.

mother.set_name("Ursula N. Nonymous");
mother.set_height(1.65);
mother.set_weight(58);

baby.set_height(0.495);
baby.set_weight(3.4);

std::cout << "Baby: " << baby.get_name() << " BMI: " << baby.bmi() << std::endl;
std::cout << "Mother: " << mother.get_name() << " BMI: " << mother.bmi() << std::endl;
std::cout << "Father: " << father.get_name() << " BMI: " << father.bmi() << std::endl;

return 0;
}

最佳答案

如果你想在函数中定义一个类,你必须在类定义中内联定义该类的每个方法。例如:

class Patient {
private: // default is private but stating explicitly here for learning purposes
std::string name; //object
int height; //object
int weight; //object
public:
Patient()
{
name="string";
height=0;
weight=0;
}
};

关于c++ - 我无法弄清楚 C++ 语法错误 "expected ` ;' before ‘{’ token ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23792156/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com