这段程序究竟对不对?
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指针已经指向一个新的对象,怎么也不可以呢?