2016-09-14 39 views
1

我想我仍然需要学习很多不仅关于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()在其计算。

这是我应该避免或不能做的事情的清单:
+制作的本地副本PersonrecommendDumbbellWeight(这样就可以避免类似GymInstructor::recommendDumbbellWeight(Person person)),因为我并不需要它减慢我的计划
+给recommendDumbbellWeight指针GymInstructor::recommendDumbbellWeight(Person *pPerson),因为我只是只读访问,因此应该避免任何错误,通过给予写入访问recommendDumbbellWeight
+ Make 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是一个常量引用。
我假设我太愚蠢,看不到非常明显的解决方案,或者我的设计中存在根本性错误。我将如何解决我的问题?

+2

“+ Make Person :: bodyMassIndex是一个const函数,因为它取决于对象的状态,在这里例如重量和高度。” **这对于非常量是不合理的。** string :: c_str()是const并且完全依赖于状态。 –

回答

3

声明的方法const有点像做一个承诺,它不会尝试修改对象。它不会拒绝你访问对象的状态,你仍然可以完美地将它称为非const对象。 所以是的,解决方案是float bodyMassIndex() const;

+0

啊,通过声明函数为'const',我总是只想到像'const float bodyMassIndex();'这样的东西。对于这种困惑感到抱歉。 – hexcoffee

+0

那么如果你想进一步推测,可以说非静态方法具有“不可见”参数,并且该方法的cv限定符适用于该参数 – Ap31

0

申报方法为const,因为它是一个getter反正 float bodyMassIndex() const;

0

Person::bodyMassIndex()不应该是const的要求是不合理和相当可笑的。 Person::bodyMassIndex()不应该是const的唯一参数是它实际上更改Person对象的状态。它没有。

因此,首先有Person::bodyMassIndex() non-const是一个错误。班级设计中的错误。