最近新学习类,我整理了一下自己的学习心得和体会。
类有三个重要的特征,即封装、继承和多态。
简单结构体应用
#include <iostream>
using namespace std;
struct Dot{
int a;
int b;
};
int main(){
Dot dot;
dot.a=0;
dot.b=1;
cout<<"dot.a="<<dot.a<<endl;
cout<<"dot.b="<<dot.b<<endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
struct Dot{
int a;
int b;
void print(){
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
};
int main(){
Dot dot;
dot.a=0;
dot.b=1;
dot.print();
system("pause");
return 0;
}
#include <iostream>
using namespace std;
class Dot{
public:
int a;
int b;
void print(){
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
};
int main(){
Dot dot;
dot.a=0;
dot.b=1;
dot.print();
system("pause");
return 0;
}
#include <iostream>
using namespace std;
class Rectangle{
private:
double length,width;
public:
Rectangle(double a,double b);
void area(){
cout<<"Area of Rectangle is:"<<length*width<<endl;
}
};
Rectangle::Rectangle(double a,double b){
length=a;
width=b;
}
int main(){
Rectangle rect(2,9);
rect.area();
system("pause");
return 0;
}
在主函数main()中,没有直接调用该构造函数Rectangle(),只是声明了对象rect,系统自动调用了构造函数并完成了初始化的功能。
如果涉及带有默认参数的构造函数,在定义对象时必须给构造函数传递参数,否则构造函数不被执行。而实际应用中,也可以把构造函数定义成带有默认参数值的构造函数,这样在定义对象时可以不指定实参,用默认参数值来初始化数据成员。
#include <iostream>
using namespace std;
class Rectangle{ //定义类
private:
double length,width; //定义私有数据成员
public:
Rectangle(double a=0.0,double b=0.0); //声明带有默认参数的构造函数
double area(); //声明成员函数
};
Rectangle::Rectangle(double a ,double b){ //定义构造函数
length=a;
width=b; //数据成员初始化
}
double Rectangle::area(){ //定义成员函数
double s;
s=length*width;
return s; //返回面积
}
int main(){
Rectangle ob1; //创建对象1
Rectangle ob2(1.5,2.0); //创建对象2
Rectangle ob3(2.5); //创建对象3
cout<<ob1.area()<<endl;
cout<<ob2.area()<<endl;
cout<<ob3.area()<<endl;
system("pause");
return 0;
}
//ob1在定义时没有传递参数,所以length和width取构造函数的默认值初始化值0.0,对象3则将2.5传递给第一个length。