![]() |
#2
rjsp2019-06-20 08:45
因为 "**_***" 是字符串常量,char _name[20] 是可以修改的变量,因此前者不能自动转换为后者。
另外,你的代码错误太多了, 比如 name[20] = _name[20]; 其中 name[20] 和 _name[20] 都不存在 比如 int i = -1; while (name[i] ……,其中 name[-1] 访问了不属于自己的内存。 我帮你改了一下 ![]() #include <iostream> #include <string> class Student { public: Student(); Student( const char* name, unsigned age, double chinese, double english, double math ); private: std::string name_; unsigned age_; double chinese_, english_, math_; friend std::istream& operator>>( std::istream& is, Student& st ); friend std::ostream& operator<<( std::ostream& os, const Student& st ); }; Student::Student() : name_(), age_(), chinese_(), english_(), math_() { } Student::Student( const char* name, unsigned age, double chinese, double english, double math ) : name_(name), age_(age), chinese_(chinese), english_(english), math_(math) { } std::istream& operator>>( std::istream& is, Student& st ) { return std::getline(is,st.name_) >> st.age_ >> st.chinese_ >> st.english_ >> st.math_; } std::ostream& operator<<( std::ostream& os, const Student& st ) { return os << st.name_ << '\n' << st.age_ << '\n' << st.chinese_ << '\n' << st.english_ << '\n' << st.math_; } using namespace std; int main( void ) { Student student; cin >> student; cout << student << endl; } 输入 尼古拉斯 赵四 输出50 90 91 92 尼古拉斯 赵四 50 90 91 92 |
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include<Windows.h>
using namespace std;
class Student{
public:
int age;
char name[20];
int Chinese;
int English;
int Math;
Student(int age, char name[20], int Chinese, int English, int Math);
void WhileGetchar(char name[20]);
void PrintStudent();
};
Student::Student(int _age, char _name[20], int _Chinese, int _English, int _Math) {
age = _age;
name[20] = _name[20];
Chinese = _Chinese;
English = _English;
Math = _Math;
}
void Student::WhileGetchar(char name[20]) {
int i = -1;
while (name[i] != '\n') {
i++;
name[i] = getchar();
}
}
void Student::PrintStudent() {
cout << age << endl << name << endl << Chinese << endl << English << endl << Math << endl;
}
int main()
{
int age, Math, Chinese, English;
cin >> age >> Math >> Chinese >> English;
Student student(age,"**_***",Chinese,English,Math);//报错在这一行
student.WhileGetchar(student.name);
student.PrintStudent();
return 0;
}