报错代码
class teacher{
public:
string name = "王老师";
int age = 28;
void printTech() const{
// age = 30;
cout << "常函数不能修改成员变量的值"<< endl;
cout << name << age << endl;
}
};
int main() {
const teacher t("夏老师",28);
return 0;
}
原因
创建对象时,没有提供接受两个参数的构造函数
修改后的代码
class teacher{
public:
string name = "王老师";
int age = 28;
teacher(string name,int age){
cout << "有参构造" << endl;
}
void printTech() const{
// age = 30;
cout << "常函数不能修改成员变量的值"<< endl;
cout << name << age << endl;
}
};
int main() {
const teacher t("夏老师",28);
return 0;
}