c++ study diary5

16.1.25

一、对象的动态建立和释放

使用new和delete,动态分配和撤销内存。

例如:new box

在此空间中存放一个box类对象,同时调用该类的构造函数,以使该对象初始化。但用户无法访问因为此对象无对象名,用户也不知道地址。

Box *pt;

Pt=new box;\\在pt中存放新建对象的起始地址

二、对象的赋值和复制

①对象的赋值

Student stud1,stud2;

Stud2=stud1;

②对象的复制

类名对象2(对象1),用对象1复制出对象2

类名对象名1=对象名2,对象2复制对象1.

三、静态成员

如果希望各对象中的数据成员的值是一样的,就可以定义为静态数据成员。

Class box

{public:

  Intvolume();

Private:

  Staticint height;

  Intwidth;

  Intlength;

};

Int box::height=10;

静态成员可以初始化,但只能类体外进行初始化。不能用初始化表对数据进行初始化!!

静态成员函数

Static intvolume();

静态成员函数是类的一部分而不是对象的一部分。如果要在类外调用公用的静态成员函数,要用类名和域运算符“:”。

Box::volume()

静态成员函数没有this指针,所以不能访问非静态成员

using namespacestd;

class time

{public:

         time(int,int,int);

         friend void display(time&);

 private:

        inthour;

        intminute;

        intsec;

        

};

time::time(inth,int m,int s){

         hour=h;

         minute=m;

         sec=s;

}

voiddisplay(time&t)

{cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;

}

int main(){

         time tl(10,13,56);

         display(tl);

         return 0;

}

四、类模板

    对于类的声明来说,其功能是相同的,仅仅是数据类型不同。

声明Template <classnumtype>

定义:类模板名<实际类型名> 对象名(参数表)

如:compare<int>cml(4,6)

例子:

using namespacestd;

template<classnumtype>

class compare

{public:

         compare(numtype a,numtype b);

         numtype max();

         numtype min();

         private:

         numtype x,y;

};

template<classnumtype>

compare<numtype>::compare(numtypea,numtype b){

         x=a;

         y=b;

}

template<classnumtype>

numtypecompare<numtype>::max(){

         return(x>y)?x:y;

}

template<classnumtype>

numtypecompare<numtype>::min(){

         return(x<y)?x:y;

}

int main(){

         compare<int> cmpl(3,7);

         cout<<cmpl.max()<<endl;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值