读书人

请求帮忙解决error C2264的有关问题

发布时间: 2012-12-17 09:31:40 作者: rapoo

请求帮忙解决error C2264的问题
#include<iostream>
#include<iomanip>
using namespace std;
//--------------------------
class Date{
int year,month,day;
public:
void set(int y,int m,int d);
void set(string& s);
bool isLeapYear();
void print();
};
void Date::set(int y,int m,int d){
year=y; month=m; day=d;
}
void Date::set(string& s){
year=atoi(s.substr(0,4).c_str());
month=atoi(s.substr(5,2).c_str());
day=atoi(s.substr(0,2).c_str());
}
bool Date::isLeapYear(){
return (year%4==0 && year%100!=0)||(year%400==0);
}
void Date::print(){
cout<<setfill('0');
cout<<setw(4)<<year<<'-'<<setw(2)<<month<<'-'<<setw(2)<<day<<'\n';
cout<<setfill(' ');
}
int main(){
Date d,e;
d.set(2000,12,6);
e.set("2005-05-05");
e.print();
if(d.isLeapYear())
d.print();
}


编译后的结果:


D:\VC++的Test\第八章\f0804\f0804.cpp(36) : error C2664: 'void __thiscall Date::set(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &)' : cannot convert parameter 1 from 'char [11]' to 'class std::basic_string<
char,struct std::char_traits<char>,class std::allocator<char> > &'
A reference that is not to 'const' cannot be bound to a non-lvalue
D:\VC++的Test\第八章\f0804\f0804.cpp(40) : warning C4508: 'main' : function should return a value; 'void' return type assumed
Error executing cl.exe.

f0804.exe - 1 error(s), 1 warning(s)
[最优解释]

#include<iostream>
#include<iomanip>
using namespace std;
//--------------------------
class Date{
int year,month,day;
public:
void set(int y,int m,int d);
void set(string& s);
bool isLeapYear();
void print();
};
void Date::set(int y,int m,int d){
year=y; month=m; day=d;
}
void Date::set(string& s){
year=atoi(s.substr(0,4).c_str());
month=atoi(s.substr(5,2).c_str());
day=atoi(s.substr(0,2).c_str());
}
bool Date::isLeapYear(){
return (year%4==0 && year%100!=0)
[其他解释]
更改一下:

e.set(string("2005-05-05"));

[其他解释]
(year%400==0);
}
void Date::print(){
cout<<setfill('0');
cout<<setw(4)<<year<<'-'<<setw(2)<<month<<'-'<<setw(2)<<day<<'\n';
cout<<setfill(' ');
}
int main(){
Date d,e;
string strDate("2005-05-05");


d.set(2000,12,6);
//e.set("2005-05-05");
e.set(strDate);
e.print();
if(d.isLeapYear())
d.print();
}



问题出在Date的set方法上,你定义的参数是string的引用,那么程序中必须有一个实际存在的string变量传给函数


[其他解释]
非常谢谢两位
[其他解释]
也可以定义你的set函数为常引用形式的,因为用户怎么知道不可以传递常量为实参,因此可以这样定义成员函数
void set(const string& s);
void Date::set(const string& s){
year=atoi(s.substr(0,4).c_str());
month=atoi(s.substr(5,2).c_str());
day=atoi(s.substr(0,2).c_str());
}
这样就能够通过编译了。

读书人网 >C++

热点推荐