私有和公有成员的定义和使用,构造函数的定义:
#include <iostream>
using namespace std;
class Sales_item
{
public:
Sales_item(const std::string &book, unsigned units, double amount) //这里的string要用const修饰
: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) //不能定义为const
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
}
private:
std::string isbn; //书号
unsigned units_sold; //销售数量
double revenue; //总金额
};
class Person //对数据和函数进行封装
{
//成员,默认是私有的
public:
Person(const std::string &nm,const std::string &addr):name(nm),address(addr) //初始化列表
{
/*name = nm; //赋值
address = addr;*/
}
std::string getName() const //只读,定义为const
{
return name;
}
std::string getAddress()
{
return address;
}
private: //进行数据隐藏
std::string name;
std::string address;
};
int main()
{
Person a("张飞", "花园街5号");
cout << a.getName() << endl;
cout << a.getAddress() << endl;
Sales_item x((string("0-399-82477-1")), 2, 20.00);
Sales_item y((string("0-399-82477-1")), 6, 48.00);
if (x.same_isbn(y))
x.add(y);
cout << "两个销售单的平均价:" << x.avg_price() << endl;
cout << "Hello 类!" << endl;
return 0;
}
类型别名,内联函数
#include <iostream>
using namespace std;
class Screen
{
public:
typedef std::string::size_type index;
//内联的成员函数
Screen(index ht = 0, index wd = 0) :contents(ht * wd,'A'),cursor(0),height(ht),width(wd)
{}
//char get() const
//{
// return contents[cursor];
//}
//char get(index r, index c) const
//{
// index row = r * width;
// return contents[row + c];
//}
//函数声明
Screen(index ht, index wd, const std::string& conts);
char get() const;
char get(index r, index c) const;
private:
std::string contents;
index cursor;
index height, width;
};
Screen::Screen(index ht, index wd, const std::string& conts):contents(conts),cursor(0),height(ht),width(wd)
{}
char Screen::get() const //加上inline还是内联的,
{
return contents[cursor];
}
inline char Screen::get(index r, index c) const
{
index row = r * width;
return contents[row + c];
}
int main()
{
Screen a(10,100);
cout << a.get() << endl;
cout << a.get(2, 8) << endl;
Screen b(3, 6, "hello screen class");
cout << b.get() << endl;
cout << b.get(1, 2) << endl;
Screen::index idx; //类型别名可以在类的外部使用
return 0;
}