class Sale_data
{
public:
int id = 5;//在类内部,不再函数体内的话不能直接初始化
Sale_data() {}
Sale_data(string &s) :bookNo(s) {}
~Sale_data() {}
string isbn() const
{
return bookNo;
}
//inline 定义在类内部的成员函数 是自动内联的
//常量成员函数不能改变调用他的对象的内容
inline string getStr() const
{
//++id;//常量成员函数不能改变对象内容
return bookNo;
}
inline Sale_data & getThis()
{
bookNo += "bbb";
return *this;//返回的是自身的引用,作为左值
}
int getCount() const
{
++count;
return count;
}
//一个const成员函数如果以引用的形式返回*this,那么它的返回类型将是常量引用
const Sale_data & getcThis() const
{
++count;
return *this;
}
//如果返回的不是引用,则返回副本
Sale_data getrThis()
{
return *this;
}
//友元函数 友元类
//类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。
//尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。
private:
string bookNo;
//可变数据成员,mutable即使是在const成员函数内也可以改变成员数据
mutable int count = 0;
};
class Box
{
public:
friend void printWidth(Box box);//友元函数
friend class BigBox; //友元类
void setWidth(double wid);
private:
double width;
void show(){}
};
//成员函数
void Box::setWidth(double wid)
{
width = wid;
}
//printWidth不是任何类的成员函数
void printWidth(Box box)
{
box.show();
cout << "friend function box.width = " << box.width << endl;
}
class BigBox
{
public:
void Print(double width, Box &box)
{
box.setWidth(width);
box.show();
//如果不被定义成box的友元类不能使用私有变量box.width
cout << "friend class box.width = " << box.width << endl;
}
private:
};
int main()
{
string str("aaa");
Sale_data *sale(new Sale_data(str));
cout<<sale->isbn()<<endl;
cout << sale->getThis().getStr() << endl;
cout << sale->getStr() << endl;
cout << sale->getCount() << endl;
cout << sale->getcThis().getCount() << endl;
Sale_data salecopy = sale->getrThis();
salecopy.id = 20;
cout << sale->id << endl;
Box box;
box.setWidth(3.1415);
printWidth(box);
BigBox bigBox;
bigBox.Print(1.1111, box);
return 0;
}