C++ :函数中无需改变传入参数的值时,定义时把 “Item & x ” 都改成 \“const Item & x\“

//f080204.h

#ifndef f080204
#define f080204

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

class Date {
int year, month, day;

public:
     void set(int y, int m, int n);
  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<<"\n";cout<<setfill(' ');
}

#endif

//f080204.cpp#include"f080204.h"

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

错误:

Compiling...
f080204.cpp
F:\C++练习\f080204.cpp(6) : 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
执行 cl.exe 时出错.

解决:将蓝色字体分别改为:

  void set(const string& s);

void Date::set( const string &s){

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值