首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用私有方法设置类变量

使用私有方法设置类变量
EN

Stack Overflow用户
提问于 2014-07-02 11:31:44
回答 2查看 81关注 0票数 0

比如说,我们有一个具有内部状态的类,作为私有变量实现的类和确定该状态的方法。用方法设置变量的oop方法是什么:

代码语言:javascript
复制
class Car
{
..
private:
float speed_;
float calculate_optimal_speed();
..}

让一个函数calculate_optimal_speed()返回其体内的varible speed_还是一个void set_speed()方法更好呢?

比如说,我们有一个很大的方法control_the_car()。在代码的进一步开发中,哪些是首选的,并将减少问题:

代码语言:javascript
复制
float calculate_optimal_speed();
control_the_car()
{
..
speed_ = calculate_optimal_speed();
}

代码语言:javascript
复制
void set_optimal_speed();
control_the_car();
{
..
set_optimal_speed();
}

一方面,实现set_optimal_speed()允许在代码修改较少的情况下更改speed_变量的类型。另一方面,返回一个值允许在我再次需要时重用该函数。这里有经验法则吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-02 11:38:41

这里有经验法则吗?

是的:编写最简单的实现来满足您的需求。如果你以后需要不同的东西,重构。

这意味着您可能应该使用set_optimal_speed();实现,除非您有不需要在类的私有状态下设置的速度(如果需要,则创建一个返回速度的函数,然后根据该函数实现set_optimal_speed(); )。

票数 1
EN

Stack Overflow用户

发布于 2014-07-02 11:53:06

拥有getter和setter可以帮助您维护和组织代码。

代码语言:javascript
复制
class Car {
private:
   // A private variable named speed_ of type float
   float speed_;
   float calculate_optimal_speed();
public:
   // Constructor
   Car(float x) { speed_ = x; }
   // OR
   Car(float speed_) { this->speed_ = speed_; }

   // A getter for variable speed_ of type T receives no argument and return a value of type float
   float getspeed_() const { return speed_; }

   // A setter for variable speed_ of type float receives a parameter of type float and return void
   void setspeed_(float x) { speed_ = x; }
   // OR
   void setspeed_(float speed_) { this->speed_ = speed_; }
}

control_the_car()
{
..
 x = calculate_optimal_speed()
 void setspeed_(float x) { speed_ = x; } ;
}

这样,如果您需要更新速度变量,可以使用Setter更新它

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24530009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档