在这种情况下,我是否需要使用指针
Do I need to use a pointer in this case?
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 对象一起使用!
相关文章:
- 新分配指向函数的指针是否合法?
- 在函数结束后使用指向变量的指针是否安全?
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 经过最后一个数组元素末尾的指针是否应该等于超过整个数组末尾的指针?
- 传递给放置 new 的指针是否是指向其对象表示形式的非 UB 指针?
- 'this'指针是否可以在 c++ 标头声明中使用?
- C++ 在向量中使用指针是否可能导致指针悬空?
- 唯一指针是否在堆或堆栈上分配内存?
- 将基本实例指针强制转换为派生实例指针是否合法?(实例不是派生实例)
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何判断指针是否是指向数组的指针
- 在类方法中使用 "this" 指针是否是一种好的做法?
- 如何知道指针是否已在其他地方释放
- 结构成员指针是否自动初始化为零?
- 为静态类创建指向对象的指针是否合法?
- 新的自动关键字指针是否会自行删除?
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 检查指针是否指向矢量元素
- 如何创建一个带锁的指针数组并检查指针是否空闲?
- 在映射中插入更多元素后,指向 QMap 中元素的指针是否仍然有效?