这段程序究竟对不对?

nisky 2002-01-02 10:56:30
#include <iostream>

class Cat
{
public:
Cat();
Cat(Cat&);
~Cat();
void SetAge(int age);
int GetAge() const ;
private:
int itsAge;
};

Cat::Cat()
{
itsAge=5;
}

Cat::Cat(Cat&)
{

}

Cat::~Cat()
{

}

void Cat::SetAge(int age)
{
itsAge=age;
}

int Cat::GetAge() const
{
return itsAge;
}


const Cat * const FunctionTwo(const Cat * theCat);


int main()
{
Cat theCat;
FunctionTwo(&theCat);

return 0;
}



const Cat* const FunctionTwo(const Cat * theCat)
{

cout << "The address of parameter theCat:" << theCat << endl;
cout << "The age of theCat:" << theCat->GetAge() << endl;

const Cat * tempCat=theCat;
cout << "The address of tempCat:" << tempCat << endl;
//theCat;
theCat = new Cat;
cout << "The address of new theCat:" << theCat << endl;
cout << "The age of local theCat:"<<theCat->GetAge() << endl;
theCat->SetAge(12);
cout << "Now the age of local theCat:" << theCat->GetAge() << endl;
delete theCat;
theCat=0;
theCat=tempCat;
cout << "The age of returning theCat:" << theCat << endl;
return theCat;
}

使用g++进行编译出现以下错误提示:
in function 'const class Cat *const FunctionTwo(const class Cat
*)':warning:passing 'const Cat' as 'this' argument of 'void Cat::SetAge(int)'
discards const
我想编译器是这么解释的,把一个const Cat指针去调用可以改变对象的方法,这当然是错误的,但是我的theCat指针已经指向一个新的对象,怎么也不可以呢?
...全文
65 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yhc0125 2002-01-02
  • 打赏
  • 举报
回复
theCat 是指向常量的指针。程序不能修改常量,当theCat指针变化后,常量可能会变化,所以编译器出错。不能将指向非常量的指针赋给指向常量的指针。
Roage 2002-01-02
  • 打赏
  • 举报
回复
9494,楼上的兄弟说得对。
up up up
panjet 2002-01-02
  • 打赏
  • 举报
回复
因为const Cat已经申明为常量。
也就是在作用范围内是不可以改变的,
你想给这个常量付值编译器当然不会同意。
bary1980 2002-01-02
  • 打赏
  • 举报
回复
同意楼上,不过如果你想调用这个函数的话,最好在函数声明时用
void SetAge(int age) const;
可是你的函数体中改变了成员数据,所以即使这样定义也不对,
大虾,你只有修改const Cat * const FunctionTwo(const Cat * theCat);
为const Cat * const FunctionTwo(Cat * theCat);了

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧