请指教C++问题
来源:百度知道 编辑:UC知道 时间:2024/08/21 01:05:30
请看以下代码:
#include<iostream>
#include<string>
using namespace std;
class Student
{public:
Student(int n,string nam)
{num=n;name=nam;
}
void display()
{cout<<"num"<<num<<endl;
cout<<"name:"<<name<<endl;
}
protected:
int num;
string name;
};
class Student1:public Student
{public:
Student1(int n,char nam[],int a):Student(n,nam){age=a;}//把"char nam[]"改为string nam编译通过
void show() /*之前报错为:error C2664: '__thiscall Student1::Student1(int,char [],int)' : cannot convert parameter 2 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'char []'*/
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
{display();
cout<<"ag
#include<iostream>
#include<string>
using namespace std;
class Student
{public:
Student(int n,string nam)
{num=n;name=nam;
}
void display()
{cout<<"num"<<num<<endl;
cout<<"name:"<<name<<endl;
}
protected:
int num;
string name;
};
class Student1:public Student
{public:
Student1(int n,char nam[],int a):Student(n,nam){age=a;}//把"char nam[]"改为string nam编译通过
void show() /*之前报错为:error C2664: '__thiscall Student1::Student1(int,char [],int)' : cannot convert parameter 2 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'char []'*/
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
{display();
cout<<"ag
第一个:
Student1(int n,char nam[],int a):Student(n,nam){age=a;}
Student1的构造函数调用基类构造函数Student(n,nam),看Student(n,nam)的实现。name=nam;而name是string类型,string类型重载了运算符=,所以Ok.
如果是char[]类型,也可以说成是char*类型,由于没有重载char *的运算符=,故编译无法通过。
第二个:strcpy库函数原型为strcpy(char *,char *),而编译器不知道如何将string类型转换为char *故而报错。
第一题 char nam[]对应的类型是 Student类的 string nam,故数据类型必须相同