我想我仍然需要学习很多不仅关于C++,而且面向对象编程本身。在最近的C++项目中,我偶然遇到了一个问题:如果我有一种情况需要将某个const引用传递给某个对象,那么如何使用该对象的非const函数呢?如果我想调用const引用的非const函数,请更正OOP设计?
让我举个例子:假设我有一些数据,并以较小运算与数据的函数的类,例如
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()
在其计算。
这是我应该避免或不能做的事情的清单:
+制作的本地副本Person
内recommendDumbbellWeight
(这样就可以避免类似GymInstructor::recommendDumbbellWeight(Person person)
),因为我并不需要它减慢我的计划
+给recommendDumbbellWeight
指针GymInstructor::recommendDumbbellWeight(Person *pPerson)
,因为我只是只读访问,因此应该避免任何错误,通过给予写入访问recommendDumbbellWeight
+ Make 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
是一个常量引用。
我假设我太愚蠢,看不到非常明显的解决方案,或者我的设计中存在根本性错误。我将如何解决我的问题?
“+ Make Person :: bodyMassIndex是一个const函数,因为它取决于对象的状态,在这里例如重量和高度。” **这对于非常量是不合理的。** string :: c_str()是const并且完全依赖于状态。 –