首先定义了一个类Date
}
void Date::print()const
{
cout<<setfill('0');
cout<<setw(4)<<year<<'-'<<setw(2)
<<month<<'-'<<setw(2)<<day<<'/n';
cout<<setfill(' ');
}
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(8,2).c_str());
}
int main()
{
Date d,e;
d.set(2000,12,6);
e.set("2005-05-05");
e.print();
if(d.isLeapYear())
d.print();
return 0;
}
编译提示出错,出错的原因在于c_str()这个函数这里,简单说一下这个函数的来历作用:
实际应用中这个问题也难以避免,很多时候我们还是需要将string类型的转化为 char*来实现自定义的操作,C++标准库也为了和之前用C写的程序兼容,于是可以用string的c_str()函数。
string var = "xxoo";
char *ptr = var.c_str(); //还不能被编译
但是c_str()为了防止意外地修改string对象,返回的是const指针,所以上面这段代码是不能被编译的。正确的应该是用const指针。
string var = "xxoo";
const char *p = var.c_str(); //此时正确
const char *c_str();
有了这些基础知识,则针对上面这个例子的问题就很容易解决了。只需要加一个const 就OK了。修正后的代码如下:
}
void Date::print()const
{
cout<<setfill('0');
cout<<setw(4)<<year<<'-'<<setw(2)
<<month<<'-'<<setw(2)<<day<<'/n';
cout<<setfill(' ');
}
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(8,2).c_str());
}
int main()
{
Date d,e;
d.set(2000,12,6);
e.set("2005-05-05");
e.print();
if(d.isLeapYear())
d.print();
return 0;
}
到此结束,OVER!