答案-c++面向对象程序设计课后习题答案(谭浩强版)

void change(int n,float s) {num=n;score=s;} void display() {cout<

//可改为:void display() const {cout<

int main() {const Student stud(101,78.5); stud.display();

//stud.change(101,80.5); stud.display(); return 0; }

解法二:

#include using namespace std; class Student {public:

Student(int n,float s):num(n),score(s){}

void change(int n,float s) const {num=n;score=s;} void display() const {cout<

mutable int num; mutable float score; };

int main()

{const Student stud(101,78.5); stud.display();

stud.change(101,80.5); stud.display(); return 0; }

解法三:

#include using namespace std; class Student

{public:

Student(int n,float s):num(n),score(s){} void change(int n,float s) {num=n;score=s;} void display() {cout<

int main()

{Student stud(101,78.5); Student *p=&stud; p->display();

p->change(101,80.5); p->display(); return 0; } 8:

#include using namespace std; class Student {public:

Student(int n,float s):num(n),score(s){} void change(int n,float s) {num=n;score=s;} void display() {cout<

int main()

{Student stud(101,78.5); void fun(Student&); fun(stud); return 0; }

void fun(Student &stu) {stu.display();

stu.change(101,80.5); stu.display(); }

9:

#include using namespace std; class Product {public:

Product(int n,int q,float p):num(n),quantity(q),price(p){}; void total();

static float average(); static void display();

private: int num; int quantity; float price;

static float discount; static float sum; static int n; };

void Product::total() {float rate=1.0;

if(quantity>10) rate=0.98*rate;

sum=sum+quantity*price*rate*(1-discount); n=n+quantity; }

void Product::display() {cout<

cout<

float Product::average() {return(sum/n);}

float Product::discount=0.05; float Product::sum=0; int Product::n=0;

int main() {

Product Prod[3]={

Product(101,5,23.5),Product(102,12,24.56),Product(103,100,21.5) };

for(int i=0;i<3;i++) Prod[i].total(); Product::display(); return 0; }

10:

#include using namespace std; class Date; class Time {public:

Time(int,int,int);

friend void display(const Date &,const Time &); private: int hour; int minute; int sec; };

Time::Time(int h,int m,int s) {hour=h; minute=m; sec=s; }

class Date {public:

Date(int,int,int);

friend void display(const Date &,const Time &); private: int month; int day; int year; };

Date::Date(int m,int d,int y) {month=m; day=d; year=y; }

void display(const Date &d,const Time &t) {

联系客服:779662525#qq.com(#替换为@)