C++我的程序这个问题 应该怎么改 高手请进

来源:百度知道 编辑:UC知道 时间:2024/05/05 14:52:31
#include <iostream>
using namespace std;
class Time
{ public:
Time(int,int,int);
int hour;
int minute;
int sec;
};
Time::Time(int h,int m,int s)
{ hour=h;
minute=m;
sec=s;
}
void fun(const Time &t)
{t.hour=18;}

int main()
{Time t1(10,13,56);
fun(t1);
cout<<t1.hour<<endl;
return 0;
}
编译的时候说我这{t.hour=18;} 报错 报错信息为error C2166: l-value specifies const object 高手告诉我下怎么改

因为hour是私有变量,不能直接引用,所以把fun改成成员函数即可。
#include <iostream>
using namespace std;
class Time
{ public:
Time(int,int,int);
int hour;
int minute;
int sec;
public:void fun(int);
};
Time::Time(int h,int m,int s)
{ hour=h;
minute=m;
sec=s;
}
void Time::fun(int n){
hour=n;
}
int main()
{Time t1(10,13,56);
t1.fun(18);
cout<<t1.hour<<endl;
return 0;
}

左值不能使const。

void fun(const Time &t)
{t.hour=18;}
改成
void fun(Time &t)
{t.hour=18;}
即可!

void fun(const Time &t)
{t.hour=18;
}

参数有 const 修改参数的值当然会报错

如果函数里要修改参数值去掉 const就行了

void fun(Time &t)
{t.hour=18;
}

#include <iostream>
using namespace std;
class Time
{ public:
Time(int,int,int);
int hour;
int minute;
int sec;
};
Time::