c++类的简单使用

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值