首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

一个重载成员函数的有关问题,一个编译报错

2012-02-22 
一个重载成员函数的问题,一个编译报错我的本意是通过set重载,设置时间,但是有一个编译报错,源代码如下,大

一个重载成员函数的问题,一个编译报错
我的本意是通过set重载,设置时间,但是有一个编译报错,源代码如下,大家帮着看看,   开发工具VC++   2005   Express

#include   <iostream>
#include   <iomanip>
#include   <string>
using   namespace   std;

class   Date
{
private:

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(8,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 < <endl;
cout < <setfill( '   ');
}

int   main()
{
Date   d,   e;
d.set(2000,12,6);
e.set( "2005-05-05 ");
e.print();
if(d.isLeapYear())
d.print();
}

出错提示
void   Date::set(std::string   &)”:   不能将参数   1   从“const   char   [11]”转换为“std::string   &”


[解决办法]
void set(string& s);
==>
void set(string s);

去掉引用,
后面的函数实现中也把 & 去掉
[解决办法]
const char [11]”转换为“std::string &”
--------------------------------------
string& a=2005-05-05;
后面2005-05-05为常量即const,这样引用当然不可以了,可以这样啊
string b= "2005-05-05 "
void set(string&)
调用
set(b);
而不是set( "2005-05-05 ");
[解决办法]
把void Date::set(string& s)换成
void Date::set(const string& s)试试
[解决办法]
楼上的分析也有道理~

string& a=2005-05-05;
后面2005-05-05为常量即const,这样引用当然不可以了,可以这样啊
string b= "2005-05-05 "
void set(string&)
调用
set(b);
而不是set( "2005-05-05 ");
===================================
最好在string b= "2005-05-05 "写成string b( "2005-05-05 ");

热点排行