C++ “>>”预算符的重载出错了,求解答
#include<iostream>#include<cstring>usingnamespacestd;classstaff{protected:char*num;ch...
#include<iostream>
#include<cstring>
using namespace std;
class staff
{
protected:
char *num;
char *name;
int age;
public:
static long counter;
staff(){}
staff(char *a,char *b,int c)
{
num=new char[18];
name=new char[18];
strcpy_s(num,18,a);
strcpy_s(name,18,b);
age=c;
}
staff(staff & a)
{
strcpy_s(num,18,a.num);
strcpy_s(name,18,a.name);
age=a.age;
}
friend ostream & operator<<(ostream & a ,const staff & b)
{
a<<b.num<<endl;
a<<b.name<<endl;
a<<b.age<<endl;
return a;
}
friend istream & operator>>(istream & a ,const staff & b)
{
a>>b.num;
a>>b.name;
a>>b.age;
return a;
}
~staff()
{
delete[]num;
delete[]name;
}
};
long staff::counter =0;
void main()
{
staff a;
cin>>a;
cout<<a;
system("pause");
}
1>.\l.cpp(38) : error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'const int' (or there is no acceptable conversion)
如果把const删掉,编译不出错,运行时输入第一个数据后就出错直接跳出。 展开
#include<cstring>
using namespace std;
class staff
{
protected:
char *num;
char *name;
int age;
public:
static long counter;
staff(){}
staff(char *a,char *b,int c)
{
num=new char[18];
name=new char[18];
strcpy_s(num,18,a);
strcpy_s(name,18,b);
age=c;
}
staff(staff & a)
{
strcpy_s(num,18,a.num);
strcpy_s(name,18,a.name);
age=a.age;
}
friend ostream & operator<<(ostream & a ,const staff & b)
{
a<<b.num<<endl;
a<<b.name<<endl;
a<<b.age<<endl;
return a;
}
friend istream & operator>>(istream & a ,const staff & b)
{
a>>b.num;
a>>b.name;
a>>b.age;
return a;
}
~staff()
{
delete[]num;
delete[]name;
}
};
long staff::counter =0;
void main()
{
staff a;
cin>>a;
cout<<a;
system("pause");
}
1>.\l.cpp(38) : error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'const int' (or there is no acceptable conversion)
如果把const删掉,编译不出错,运行时输入第一个数据后就出错直接跳出。 展开
1个回答
展开全部
staff a;//调用staff(){},a.num和a.name都是野指针……
个人建议在C++中不要用char *这样的字符串,C++有string可以避免很多问题,而且用起来更顺手
个人建议在C++中不要用char *这样的字符串,C++有string可以避免很多问题,而且用起来更顺手
更多追问追答
追问
我用的是VS2005 ,字符串包含在哪个头文件里面??cstring 和string都试过了,,不行才这样做的。而且我应该怎样修改?求指教
追答
#include //这样有问题?如果只能用char*的话大概就要改成staff(){num="";name="";}不过这样要改的就多了……
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询