正确的oop设计,如果我想调用const引用的非const函数

Correct OOP-design, if I want to call non-const function of const reference?

本文关键字:const 调用 引用 函数 如果 oop 设计      更新时间:2023-10-16

我想我不仅要学习c++,还要学习面向对象编程本身。在最近的一个c++项目中,我经常遇到这样一个问题:如果我想将const引用传递给某个对象,如何使用该对象的非const函数?

让我举个例子:假设我有一个类和一个函数,其中包含一些数据和一个小的计算数据,例如

class Person
{
    private:
    float weight;
    float height;
    float age;
    ...
    public:
    float bodyMassIndex();
};

现在我又上了一堂不同专业的课,例如

class GymInstructor
{   
    private:
    float knowledge;
    int age;
    ...
    public:
    int recommendDumbbellWeight(const Person &person);
};

现在假设函数GymInstructor::recommendDumbbellWeight想要在计算中使用函数Person::bodyMassIndex()

这是我应该避免或不能做的事情清单:

  • recommendDumbbellWeight内部制作Person的本地副本(因此避免GymInstructor::recommendDumbbellWeight(Person person)之类的东西),因为我不需要这样做,它会减慢我的程序
  • recommendDumbbellWeight一个指针,像GymInstructor::recommendDumbbellWeight(Person *pPerson),因为我只需要只读访问,因此应该避免任何错误,给recommendDumbbellWeight写访问
  • 使Person::bodyMassIndex成为const函数,因为它依赖于对象的状态,例如weightheight
  • 将函数bodyMassIndex()移动到其他类,因为它使用Person的数据,所以没有真正的理由为什么另一个对象应该执行该计算。如果是这样,我就必须将所有数据传递给另一个类。
  • 说,GymInstructor::recommendDumbbellWeight需要像Person::bodyMassIndex()这样的小计算的更多结果,那么我也应该避免只传递像GymInstructor::recommendDumbbellWeight(float bodyMassIndex, float experience, float fitness, ...这样的计算结果,因为它会使我的参数列表看起来很难看,并产生不必要的代码。

那么实际上还剩下什么呢?我想在GymInstructor::recommendDumbbellWeight(const Person &person)中调用Person::bodyMassIndex(),但是我不能,因为person是一个const引用。
我想,要么是我太笨了,看不到显而易见的解决方案,要么是我的设计存在根本性的错误。我该如何解决我的问题?

声明一个方法const有点像承诺它不会试图修改对象。它不会拒绝您访问对象状态,并且您仍然可以为非const对象调用它。是的,解决方案是float bodyMassIndex() const;

声明方法为const,因为它是getterfloat bodyMassIndex() const;

要求Person::bodyMassIndex()不应该是const是不合理的,相当荒谬。Person::bodyMassIndex()不应该是const的唯一理由是它实际上改变了Person对象的状态。它不是。

因此,首先将Person::bodyMassIndex()设置为非const是一个bug。类设计错误

相关文章: