使用操作符作为mutator方法

Using operators as mutator methods

本文关键字:mutator 方法 操作符      更新时间:2023-10-16

我正在研究一本书中的一个例子,他们在类定义中给了我们原型(我认为它被称为!),然后他们希望我们像在cpp文件中那样为类定义方法。我在理解mutator方法方面有困难,特别是在这种情况下使用运算符。当你让他们成为类的"朋友"时,这更有意义,但在这种情况下,他们没有。我似乎不知道它会怎么做。任何帮助都太好了!

类类型为"Mail":

Mail operator=(const Mail& rValue);
Mail operator+(int ounces);

它们的意义在于,当我们稍后在main中创建对象mailItem1时,我们想要添加到它的一个属性(weight)

mailItem1 = mailItem1 + ADDITIONAL_WEIGHT;

我知道你不一定要看到所有的东西,但这是整个班。

class Mail
{
    // Public Interface
public:
    // Class Constructor(s)
    Mail();
    Mail(const char* type, double perOunceCost, int weight);
    Mail(const Mail& other);
    // Class Destructor
    ~Mail()
    { }  // Nothing to do, included for completeness
    // Mutator Methods
    Mail operator=(const Mail& rValue);
    Mail operator+(int ounces);
    // Observer Methods
    double getCost() const;
    friend ostream& operator<<(ostream& stream, const Mail letter);
private:
    // Class "static, const" Constant Values
    static const int TYPE_SIZE = 30;
    static const char FIRST_CLASS[];
    static const double FIXED_COST;
    static const int DEFAULT_WEIGHT = 1;
    // Variable Declarations
    char type[TYPE_SIZE];
    int weight;
    double perOunceCost;
};

我很困惑这到底是如何工作的,希望得到一些帮助。谢谢!

您应该看看I/O操纵符是如何工作的。他们做你想做的事。

解释如下:流操作符是如何工作的?

你试图对+操作符做与标准库对<<所做的相同的事情。

看一下std::endl(无参数),std::setw(有一个参数)的定义。

我很想知道你在用什么书。这是一个非常糟糕的例子,它展示了非常糟糕的类设计。