枚举器 C++ 的 setter 和 getter 方法

setter and getter method for enumerator c++

我有以下代码,我正在尝试为枚举器编写 getter 和 setter 方法。有人可以更正我的代码吗,因为经过多次尝试我仍然会出错。感谢您对此的任何帮助!

///in the header file

    class Car{

    private:    

        enum weight{small, medium, large};
    public:


      Car();


      int getWeight() const; 



      void setWeight(weight w);

    };
////// in the car.cpp file
//default constructor
Car::Car(){

    weight =small;

}

      weight Car::getWeight() const{
        return weight;
      }



      void Car::setWeight(weight w){
        weight = w;
      }

问题 1:

enum weight{small, medium, large};

是类型的声明,不是变量。在这一点之后,您可以创建可以设置和获取的 weight 类型的变量。随着

enum weight
{
    small, medium, large
};
weight mWeight;

您现在有一个 class 成员 mWeight,您可以将其与 getter 和 setters 一起使用。

但这对你没有多大好处。

问题 2:

weightprivate,所以 class 之外的人都不能看到和使用这种类型,因此 void setWeight(weight w); 调用者无法进行weight 传递给函数。

通过将 enum weight 的定义移动到 public 块然后交换 publicprivate 块的顺序以便 weight 对 class 中需要它的每个人可见。

class Car
{
public:
    enum weight
    {
        small, medium, large
    };


    Car();

    int getWeight() const;

    void setWeight(weight w);

private:
    weight mWeight;
};

问题 3:

之间不匹配
int getWeight() const;

weight Car::getWeight() const

似乎是正确的版本returns权重,所以

class Car
{
public:
    enum weight
    {
        small, medium, large
    };


    Car();

    weight getWeight() const;

    void setWeight(weight w);

private:
    weight mWeight;


};

问题 4:

没有weight这样的东西。只有祖尔。对不起。只有 Car::weight,所以在编译器知道一个函数是 Car 的一部分之前,您需要明确。

weight Car::getWeight() const{
    return weight;
  }

需要成为

Car::weight Car::getWeight() const{
    return weight;
  }

旁注:当您有 setter 和不受限制的吸气剂时,您也可以创建变量 public。使成员变量 private 的全部意义在于保护对象的状态。如果任何局外人可以在对象不知情的情况下随意更改变量,那么您将遇到难以追踪的错误。

在像上面这样的小例子中它并不那么重要,但是如果你有一个带计数器的 class 并且当该计数器达到 42 时应该发生一些重要的事情。然后一些小丑出现并使用这个 setter

void setImportantNumber(int val)
{
    importantNumber = val;
}

要将值设置为 43?封装对任何人都没有多大好处,因为 setter 违反了封装。

另一方面

void setImportantNumber(int val)
{
    if (val) < 42)
    {
        importantNumber = val;
    }
    else if (val == 42)
    {
        importantNumber = 0;
        doSomethingImportant();
    }
    else
    {
        cerr << "I'm afraid I can't let you do that, Dave.\n"
    }
}

防止一些愚蠢行为。

根据上面发布的信息,我更改了如下所示的代码并且成功了。谢谢!

//Car.h:    
 enum weight
    {
        small, medium, large
    };


class Car{
 private:
   weight mWeight;

 public:
  Car();
  weight getWeight() const;
};


//Car.cpp file
    Car::Car(){    
    mWeight =  large;

}

weight Car::getWeight() const{
    return mWeight;
 }