使用操作符作为mutator方法
Using operators as mutator methods
我正在研究一本书中的一个例子,他们在类定义中给了我们原型(我认为它被称为!),然后他们希望我们像在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(有一个参数)的定义。
我很想知道你在用什么书。这是一个非常糟糕的例子,它展示了非常糟糕的类设计。相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 使用final修饰符和mutator方法
- 使用操作符作为mutator方法