C++的,const;

来源:百度知道 编辑:UC知道 时间:2024/06/14 17:35:29
#include <iostream>
using namespace std;
class cat
{
public:
void getage(int age_2);
int setage() const;//按书的这样做.为什么会出错呢?
void outage();
private:
int age_1;
};
void cat::getage(int age_2_ptr)
{
age_1=age_2_ptr;
}
int cat::setage()
{
return age_1;
}
void cat::outage()
{
cout<<"cat"<<endl;
}
int main()
{
cout<<"Enter age about cat"<<endl;
cat mao;
int a;
cin>>a;
mao.getage(a);
cout<<"mao is a cat who is"<<mao.setage()<<"years old"<<endl;
mao.outage();
return 0;
}
//实在不好意思,没分了,呵呵.

//实现时候也要申明是const
#include<iostream>
using namespace std;
class cat
{
public:
void getage(int age_2);
int setage() const;//按书的这样做.为什么会出错呢?
void outage();
private:
int age_1;
};
void cat::getage(int age_2_ptr)
{
age_1=age_2_ptr;
}
int cat::setage() const//实现时候也要申明是const
{
return age_1;
}
void cat::outage()
{
cout<<"cat"<<endl;
}
int main()
{
cout<<"Enter age about cat"<<endl;
cat mao;
int a;
cin>>a;
mao.getage(a);
cout<<"mao is a cat who is"<<mao.setage()<<"years old"<<endl;
mao.outage();
return 0;
}

多用VC调试啊,会指出你错在那里的,你看看就知道了。下面是修改后的代码。声明跟实现要相同
#include <iostream>
using namespace std;
class cat
{
public:
void getage(int age_2);
int setage() const;//按书的这样做.为什么会出错呢?