正确的oop设计,如果我想调用const引用的非const函数
Correct OOP-design, if I want to call non-const function of const reference?
我想我不仅要学习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
函数,因为它依赖于对象的状态,例如weight
和height
。 - 将函数
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。类设计错误
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 使用共享指针的函数调用,其对象应为 const
- 如何从构造函数副本 T(const T&)调用对象 T?
- 在gcc中意外调用了Const重载.编译器错误或兼容性修复程序
- 不允许运算符 const 参数调用 const 成员函数
- "No-Const Pointer to Const "调用功能
- 在字符串函数中抛出'char const*'实例后调用的终止
- 调用'myStud::myStud(int, const char [5], int, int, int)'没有匹配函数
- 为什么我的编译器在调用 const getter 函数时抛出"转换丢失(const)限定符"错误?
- test1.cpp:9:77:错误:对"(const std::normal_distribution) <double>(std::mt19937&)"的调用不匹配
- 为什么我可以调用一个从const方法更改成员的方法
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 如何在单个模板调用中传递const_iterator和非const迭代器
- 在循环条件中调用const vector size()似乎缺少优化
- C++通过 const 引用传递时不调用派生类函数
- 当我调用 main 中使用 const 对象的 const 函数时,不断出现错误
- 非常量调用 const 成员函数失败,只读位置C++
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- 使用"const&"调用模板?
- Const调用操作符调用绑定的非Const成员函数