在这种情况下,我是否需要使用指针

Do I need to use a pointer in this case?

本文关键字:指针 是否 这种情况下      更新时间:2023-10-16
class Cat{
           private:
           float weight;
           int age;
           public:
           float getweight();
           bool compareweight(Cat*);
};
Cat::getweight(){
return weight;
}
bool Cat::compareweight(Cat* other){
return weight > other->weight;
}

我是否需要在函数 compare weight 中使用 Cat 指针,或者我可以使用堆栈对象吗?

传递对象的最佳方法是通过常量引用(如果您不更改它们(。 这将避免复制(如传递指针(,但确保您有一个项目,并且不允许您修改对象。

bool Cat::compareWeight(const Cat& other)

是您理想情况下使用的。

下一个最佳替代方案是指向 const 对象的指针

bool Cat::compareWeight(Cat const* other)

但这更有可能出现传入无效对象的问题;因此不是首选对象。

如果你使用

bool Cat::compareweight(Cat other)

你会得到一个几乎不需要的 Cat 对象副本。因此,您应该使用指针或引用。

bool Cat::compareweight(const Cat& other) const
{ return other.weight > weight ; }
bool Cat::compareweight(const Cat* other) const
{ return other->weight > weight; }

另外:您应该将方法声明为 const,因为这些方法没有更改对象的内容,您也可以使指针和引用成为 const,因为它们也没有更改与它们对应的对象。如果你不这样做,你就不能将你的方法与它们的 const 对象一起使用!