首页 > 试题广场 >

CandyBar结构包含3个成员。第一个成员存储candy

[问答题]

CandyBar结构包含3个成员。第一个成员存储candy bar的品牌名称;第二个成员存储candy bar的重量(可能有小数);第三个成员存储candy bar的热量(整数)。请编写一个程序,它使用这样的函数,即将Candy Bar的引用、char指针、double和int作为参数,并用最后3个值设置相应的结构成员。最后3个参数的默认值分别为“Millennium Munch”、2.85和350。另外,该程序还包含一个以Candy Bar的引用为参数,并显示结构内容的函数。请尽可能使用const。

#include <iostream>
#
include <string>
using namespace std;

struct CandyBar {
    string company;
    double weight;
    int calories; 
};
// const 加在函数前后区别
// const 加在函数前面普通函数或成员函数(非静态成员函数)前均可加const修饰,表示函数的返回值为const不可修改
// 函数后加const:只有类的非静态成员函数后可以加const修饰,表示该类的this指针为const类型,不能改变类的成员变量的值
// 即成员变量未read only
const void print (CandyBar &candy, const string str="Millennium Munch", const double weight=2.85, const int calories=350)
{
    candy.company = str;
    candy.weight = weight;
    candy.calories = calories;
}

int main(int argc, char const *argv[])
{
    CandyBar candy;
    print(candy);
    cout << candy.weight;
    return 0;
}
发表于 2020-03-11 14:59:53 回复(0)