//类定义
#include<iostream>
#include<string>
using namespace std;
class Person //要定义一个类(类其实是封装),就写class,类的内部可以有成员,也可以没有成员。
{
//成员,数据成员或者是函数成员
//数据成员都定义成私有的,没写默认是私有的
//这个人有两个数据成员
//访问标号实施抽象和封装:public private protected
public:
Person(const std::string &nm, const std::string &addr) :name(nm), address(addr)
{
// name = nm;
// address = addr;
}
std :: string getName()
{
return name;
}
std::string getAddress()
{
return address;
}
private:
std:: string name;//数据成员是公有的,函数成员是公有的
std:: string address;//私有的成员只能在内部使用
};
class Sales_item
{
public:
Sales_item(std::string &book, unsigned units, double amount)
:isbn(book), units_sold(units), revenue(amount)
{
}
double avg_price() const//平均利润
{
if (units_sold)
return revenue / units_sold;
else
return 0;
}
bool same_isbn(const Sales_item &rhs) const
{
return isbn == rhs.isbn;
}
void add(const Sales_item &rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
}
private:
std::string isbn;//书号
unsigned units_sold;//销售数量
double revenue;//总金额
};
int main()
{
Person a("nill","bill");//保存在私有的数据成员里
a.getName();
a.getAddress();
cout << a.getName() << "," << a.getAddress() << endl;//显示nill和bill
Sales_item x(string("0-399-82-477-1"), 5, 20);
Sales_item y(string("0-399-82-477-1"), 6, 48);
cout << x.avg_price() << endl;
if (x.same_isbn(y))
x.add(y);
cout << x.avg_price() << endl;
cout << y.avg_price() << endl;
cout << "HELLO LEI" << endl;
system("pause");
return 0;
}
c++学习笔记-类1
猜你喜欢
转载自blog.csdn.net/weixin_42655231/article/details/82467498
今日推荐
周排行