【发布时间】:2014-11-12 05:50:31
【问题描述】:
在学习了如何通过定义返回类型为“对类 C 对象的引用”(即 C &setHeight( int ) )的函数以及相应的“return *this”语句来级联多个 mutator 函数调用之后,我非常想知道类似的方法是否允许从单个“get”函数返回对象的数据成员。
我有一个简单的“发票”类,其中包含另一个类“日期”的对象。此数据成员对象本身包含存储假设产品(为其创建对象)的“购买日期”的标准日期的私有数据。尽管在“日期”中,三个 int 成员存储日期组件,但我想在我的“购买日期”访问器中以某种方式级联调用属于 Date 对象的三个相应的 get 函数,因为出现了一些单个访问器/get是必需的,因为这种风格似乎比使用 cout 语句完成任务更可取。换句话说,如果必须使用某些 get 函数来显示完整日期,我宁愿将其显示为格式化,在客户端(函数 main)中通过单个调用 within 打印语句,而不是由一个在 main 调用时仅打印格式化语句的函数。
//Invoice.h
#ifndef DATE_H
#define DATE_H
#include "Date.h"
...using namespace std. (Assume all other necessary libraries, classes, are included)
class Invoice {
public:
Invoice(); // Default constructor
Invoice( Date &, string );
setDateOfPurchase( int, int, int );
getDateOfPurchase();
private:
Date DateOfPurchase;
string description;
}; // end class definition
#endif
下面的成员函数定义...
//Invoice.cpp
#include "Date.h"
(Again, please assume the necessary inclusions are made here)
Invoice::Invoice(){
DateOfPurchase.month = 1;
DateOfPurchase.day = 1;
DateOfPurchase.year = 1999;
} // end Default constructor definition
Invoice::Invoice( Date &purchaseDate, string desc ):
DateOfPurchase( purchaseDate ),
description( desc )
{} // No body
Invoice &Invoice::setDateOP( int m, int d, int y ) {
// The Date class definition is not explicitly defined; please assume these simply accept
// one int argument each.
DateOfPurchase.setMonth( m );
DateOfPurchase.setDay( d );
DateOfPurchase.setYear( y );
return *this;
} // End mutator definition
用于检索存储在对象 DateOfPurchase 中的完整日期的访问器函数的标头如下所示:
Invoice &Invoice::getDateOrd(){
//gets month, day, and year, possibly through utilizing dereferenced 'this' pointer (*this)
} // end getDateOrd definition
下面的函数main...
主要内容: // 创建一个日期对象,该对象将通过引用传递给发票构造函数。 日期今天(2014 年 11 月 10 日);
Invoice firstSale( today, A corkscrew: product# 88090 );
// Cascading call to each member function of *member data object* DateOfPurchase
firstSale.setMonth( 11 ).setDay( 12 ).setYear( 2014 );
希望这演示了使用“set”函数的级联调用的基本应用。现在对于“获取”功能......(顺便说一下,我使用的是 Deitel & Deitel,2013 年,第 7 版)
【问题讨论】:
-
只需为 Date 类实现“toString()”即可。
-
@n.m.类 Myclass{public:string toString(){...}} cout