使用运算符作为mutator方法

时间:2014-05-27 22:33:10

标签: c++ class properties operator-overloading mutators

我正在研究一本书的例子,他们在类定义中给我们原型(我认为它叫!)然后他们希望我们像在cpp文件中那样定义类的方法。我无法理解mutator方法,特别是在运算符的情况下。当你让他们成为班上的“朋友”时更有意义,但在这种情况下他们没有。我似乎无法弄清楚它会如何表现。任何帮助都会很棒!

班级类型为“邮件”:

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

当我们创建对象mailItem1时,我们想要添加到其中一个属性(权重)中,它们的重点是以后的主要内容

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;
};

我很困惑它是如何工作的,并且会喜欢一些帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您应该了解I / O操纵器的工作原理。他们做你想做的事。

以下是解释:How do the stream manipulators work?

您正尝试使用标准库与&lt;&lt;。

执行的+运算符执行相同的操作。

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

我很想知道你正在使用什么书。这是一个非常糟糕的例子,表现出很差的课堂设计。