单选题
1分
有如下程序:#include <iostream>using namespace std;class Goods{ //货物类 ...
有如下程序:
#include <iostream>
using namespace std;
class Goods{ //货物类
double unit_price; //单价
int quantity; //数量
public:
Goods(double u=0.0, int q=0): unit_price(u),quantity(q){}
double getPrice()const{ return unit_price; } //返回单价
int getQuantity()const{ return quantity; } //返回数量
//增加数量
Goods operator +(int q)const{ return Goods(unit_price,quantity+q); }
};
//增加数量
Goods operator +(_________________){ return g+q; }
//输出货物信息
ostream& operator<<(ostream& os, Goods g){
cout<< "单价:"<<g.getPrice()<<','<<"数量:"<< g.getQuantity()<< endl;
return os;
};
int main() {
Goods g(35.6, 100);
cout<<g<<g+33<<25+g;
return 0;
}
若运行后的输出结果是:
单价:35.6,数量:100
单价:35.6,数量:133
单价:35.6,数量:125
则程序中下划线处缺失部分应该是( )。
#include <iostream>
using namespace std;
class Goods{ //货物类
double unit_price; //单价
int quantity; //数量
public:
Goods(double u=0.0, int q=0): unit_price(u),quantity(q){}
double getPrice()const{ return unit_price; } //返回单价
int getQuantity()const{ return quantity; } //返回数量
//增加数量
Goods operator +(int q)const{ return Goods(unit_price,quantity+q); }
};
//增加数量
Goods operator +(_________________){ return g+q; }
//输出货物信息
ostream& operator<<(ostream& os, Goods g){
cout<< "单价:"<<g.getPrice()<<','<<"数量:"<< g.getQuantity()<< endl;
return os;
};
int main() {
Goods g(35.6, 100);
cout<<g<<g+33<<25+g;
return 0;
}
若运行后的输出结果是:
单价:35.6,数量:100
单价:35.6,数量:133
单价:35.6,数量:125
则程序中下划线处缺失部分应该是( )。
参考答案: C
参考解析: 【解析】题意中,Goods类的构造函数接收一个double参数u和一个整型参数q,并使用它们初始化两个成员变量:unit_price和quantity,两个普通常量成员函数:getPrice()常量函数和getQuantity()常量函数,分别返回unit_price和quantity的值;重载加号运算符成员函数接收一个整型q,将q的值加到quantity成员上;在类定义体外,还有一个重载输出运算符函数,它通过Goods对象的成员函数输出Goods对象的两个成员;main()函数中,首先构造Goods对象g,然后调用重载输出运算符函数输出g、g+33和25+g:
输出g时,可知输出g的两个成员变量的值:单价:35.6,数量:100;返回值为引用的os对象;
输出g+33时,由于第一运算数是Goods对象,所以调用Goods类中重载的加号运算符成员函数,将33累加到g的quantity成员中,再输出:单价:35.6,数量:133;返回值为引用的os对象;
输出25+g时,由于第一运算数为整型,所以无法调用Goods类中的成员函数,需要使用外部定义的重载加号运算符函数,在函数体内再将第一运算数设置为g,可知,横线部分的第一个参数肯定是整型int,第二个参数是Goods类型,即 int q, Goods g。故本题答案为C选项。