浅学一下c++的类和对象
c++只学过其中的STL,我的思想还囿于c语言的表述,c++是面向对象的语言,需要一些思维转变,因此我们浅学一下叭~
c++的类:
class
与struct不同,class里面既有数据(变量),还有操作。成员被封闭在类之中,通过接口实现对外界的交互。
(1).类的数据类型
class类名{
private:
//私有的数据和成员函数
public:
//公用的数据和成员函数
protected:
//保护的数据和成员函数
};
private:私有数据成员和成员函数不透明,只允许本类的成员函数访问,不能在类的定义域之外被直接访问;类声明的第一部分默认为private
public:是类和外部的接口,外界通过接口与类发生联系
protected:用于类的继承和派生,允许本类的成员函数或派生类的成员函数访问
(2)定义方法
类名+对象名
Student stud1,stud2;
在声明类的同时定义对象:
class Student{
int num;
char num[20];
char sex;
void display(){
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;}
}stu1,stu2;
不出现类名,直接出现对象(很少用)
(3)对象成员的引用:
1.对象名访问对象成员
mybirthday.showdate();
2.指向类对象的指针访问对象成员
p=&mybirthday;
p->showdate()'
(4)类的成员函数
1.类外成员函数:
class Student{
private:
int num;
char name[20];
char sex;
public:
void display();
};
void Student::display(){
cout<<"num=:"<<num<<endl;
cout<<"name=:"<<name<<endl;
cout<<"sex=:"<<sex<<endl;
}
Student stud1,stud2;
2.内置成员函数
隐式声明:直接在类中声明
显式声明:类外用 inline 声明成员函数
class carea{
int x,y,area;
public:
void squarea(int vx,int vy);
};
inline void squarea(int vx,int vy){
x=vx;
y=vy;
area=x*y;
}
(5)构造函数
特点:构造函数名称与类名相同,一般声明为public,无返回值,不能被继承
构造函数可以带参,也可以重载;
#include<bits/stdc++.h>
using namespace std;
class Box{
public:
Box(int,int,int);
int volume();
private:
int height;
int width;
int length;
};
Box::Box(int h,int w,int len){
height=h;
width=w;
length=len;}
int Box::volume(){return (height*width*length);
}
int main(){
Box box1(12,25,30);
cout<<"The volume of box1 is"<< box1.volume()<<endl;
Box box2(15,30,21);
cout<<"The voulme of box2 is"<< box2.volume()<<endl;
return 0;}
运行结果:
The volume of box1 is 9000
The volume of box2 is 9450
还可以用参数初始化表实现对数据成员的初始化
即在原来函数首部的末尾加一个冒号,然后列出参数的初始化表
Box::Box(int h,int w,int len):height(h),width(w),length(len){}
拷贝构造函数:
#include<bits/stdc++.h>
using namespace std;
class ratio{
public:
ratio(int n=0,int d=1):num(n),den(d){}
ratio(ratio &r):num(r.num),den(r.den){}
void print(){cout<<num<<'/'<<den;}
private:
int num,den;
};
int main(){
ratio x(5,18);
ratio y(x);
cout<<"x=";x.print();
cout<<", y=";y.print();
return 0;}
运行结果:
x=5/18, y=5/18
(6)析构函数
对象的生命期结束后,会自动进行析构函数
析构函数不能接收参数,也没有返回类型声明
1)在函数中定义对象,函数结束时自动执行
2)定义全局对象,在函数流程离开其作用域(main结束或者调用exit)时自动执行
3)new动态建立对象,用delete释放对象时自动执行
#include<bits/stdc++.h>
using namespace std;
class student{
public:
student(int n,char *nam,char s){
num=n;
name=nam;
sex=s;
cout<<"Constructor is called"<<endl;
}
~student(){
cout<<"Destructor is called."<<endl;
}
void display(){
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
}
private:
int num;
char *name;
char sex;
};
int main(){
student stud1(10010,"Wang_Li",'f');
stud1.display();
student stud2(10011,"Zhang_Fan",'m');
stud2.display();
return 0;}
运行结果:
Constructor is called
num:10010
name:Wang_Li
sex:f
Constructor is called
num:10011
name:Zhang_Fan
sex:m
Destructor is called.
Destructor is called.