习题7-11
#include <iostream>
#include<string>
using namespace std;
struct Sales_data {
//构造函数
Sales_data() = default;
Sales_data(const string &s):bookNo(s){}
Sales_data(const string &s,unsigned n,double p):
bookNo(s),units_sold(n),revenue(p*n){}
Sales_data(istream &is);
string bookNo;
unsigned units_sold=0;
double revenue=0.0 ;
};
istream &read(istream &, Sales_data &);
int main()
{
Sales_data sale1;
cout << sale1.bookNo << " " << sale1.units_sold << " " << sale1.revenue << endl;
Sales_data sale2("You");
cout << sale2.bookNo << " " << sale2.units_sold << " " << sale2.revenue << endl;
Sales_data sale3("You", 3, 4);
cout << sale3.bookNo << " " << sale3.units_sold << " " << sale3.revenue << endl;
Sales_data sale4(cin);
cout << sale4.bookNo << " " << sale4.units_sold << " " << sale4.revenue << endl;
}
Sales_data::Sales_data(istream &is)
{
read(is, *this);
}
istream &read(istream &is, Sales_data &item)
{
double price = 0.0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price*item.units_sold;
return is;
}
习题7-12 这道题涉及到read函数包含sales_data 的调用,而定义构造函数的时候又需要已知read函数,所以先声明一下类名;
#include <iostream>
#include<string>
using namespace std;
struct Sales_data;
istream &read(istream &, Sales_data &);
struct Sales_data {
//构造函数
Sales_data() = default;
Sales_data(const string &s):bookNo(s){}
Sales_data(const string &s,unsigned n,double p):
bookNo(s),units_sold(n),revenue(p*n){}
Sales_data(istream &is) {read(is, *this);}
string bookNo;
unsigned units_sold=0;
double revenue=0.0 ;
};
int main()
{
Sales_data sale1;
cout << sale1.bookNo << " " << sale1.units_sold << " " << sale1.revenue << endl;
Sales_data sale2("You");
cout << sale2.bookNo << " " << sale2.units_sold << " " << sale2.revenue << endl;
Sales_data sale3("You", 3, 4);
cout << sale3.bookNo << " " << sale3.units_sold << " " << sale3.revenue << endl;
Sales_data sale4(cin);
cout << sale4.bookNo << " " << sale4.units_sold << " " << sale4.revenue << endl;
}
istream &read(istream &is, Sales_data &item)
{
double price = 0.0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price*item.units_sold;
return is;
}
习题7-13
Sales_data total(cin);
if(cin)
{
Sales_data tran(cin);
.....
}
习题7-14
struct Sales_data
{
Sales_data():bookNo(""),units_sold(0),revenue(0.0){}
}
习题7-15
struct Person
{
string name;
string address;
Person():name(""),adress(""){}
}
习题7-16
位置和次数没有限定。接口数据之类的写在public后面,不想让其他人看到的数据及具体实现细节程序写在private后面;
习题7-17
有
默认的访问权限不一样,struct默认数据类型是public,class默认数据类型是private;
习题7-18
封装实现了类的接口和实现的分离,隐藏了类的实现细节,用户只能接触到类的接口;
习题7-19
在我的Person类中可以将名字声明为public,地址声明为private,因为名字可以让人看见,为了安全起见,地址保守秘密;
习题7-20
类的友元函数可以访问类的非公有成员,这样就破坏了类的封装性