【问题标题】:Using operators as mutator methods使用运算符作为 mutator 方法
【发布时间】:2014-05-27 22:33:09
【问题描述】:

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

类类型为“邮件”:

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

它们的意义在于,稍后在 main 创建对象 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;
};

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

【问题讨论】:

  • 您的operator =() 应该返回对*this 的引用,而您的operator +() 应该返回一个副本。 See Operator Overloading 了解更多信息。

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


【解决方案1】:

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

这里有一个解释:How do the stream manipulators work?

您正试图对标准库对 的 + 运算符执行相同的操作

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2013-03-29
    相关资源
    最近更新 更多