类与对象

1.常函数
const Stock land=Stock("Kludgehorn");//常对象
void show() const;//常函数声明
void Stock::show() const;//常函数实现
2.对象产生前定义常量
class Bakery{
private:
const int Months;//不可以
enum{Months=12};?//可以
static const int Months=12;//可以,利用static关键字,被所有对象共享。
double costs[Months];
}

3.枚举类
enum class egg{Small,Medium,Large,Jumbo};
enum class t_shirt{Small,Medium,Large,Xlarge};
egg egg_old=egg::Large;//定义变量
t_shirt Floyd=t_shirt::Large;
不同枚举类不会产生命名冲突
4.单构造函数的隐式类型转换
Stonewt::Stonewt(double lbs);//定义单参数的构造函数
Stonewt myCat;//申明实例
myCat=19.6;//隐式调用一个参数的构造函数

explicit Stonewt(double lbs);//不允许进行隐式转换,explicit是关键字
myCat=Stonewt(19.6);//有效
myCat=19.6//无效
5.构造函数的初始化
class Queue{
private:
Node *front;
Node *rear;
int items;
const int qsize;
}
Queue::Queue(int qs):qsize(qs),front(nullptr),rear(nullptr),items(0){};
//数据成员的初始化顺序取决于在类定义时的顺序,并不等同于参数列表中的顺序

6.定义私有拷贝构造函数和重载=运算符防止对象被复制
class Queue{
private:
Queue(const Queue &q):qsize(0){}
Queue & operator=(const Queue &q){return *this;}
}
私有函数无法被类外引用,所以就无法调用拷贝构造函数和赋值运算符

posted @ 2024-08-01 16:25  zhongta  阅读(11)  评论(0)    收藏  举报