類和對象基本介紹
類的基本概念
在定義一個類和一個結構體後,發現他們的用法差不多。
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
using namespace std;
struct hero
{
char name[64];
int sex;
};
void PrintHero(struct hero &h)
{
cout << "hero:" << endl;
cout << "name = " << h.name << endl;
cout << "sex = " << h.sex << endl;
}
class Advhero
{
private: //在private下定義的成員變量和方法只能在類的內部進行訪問
int height[55];
int weight[55];
public: //訪問控制權限,在public下面定義的成員變量和成員函數,是能夠在類的內部和外部都可以訪問的
char name[64];
int sex;
void PrintAdvhero() //類和結構體不一樣,就在於類裏面可以直接添加函數
{
cout << "advhero:" << endl;
cout << "name = " << name << endl;
cout << "sex = " << sex << endl;
}
};
int main()
{
hero h; //其中hero爲數據類型,h爲變量
strcpy_s(h.name, "cherry");
h.sex = 0;
PrintHero(h); //結構體h調用PrintHero函數方式
Advhero advH; //其中Advhero爲類,advH爲對象
strcpy_s(advH.name, "Tom");
advH.sex = 1;
advH.PrintAdvhero(); //對象advH調用類裏面的函數方式
return 0;
}
類的private和public體現了類的封裝屬性,不想給外界使用的變量和函數可以放在private中。
類的封裝
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
using namespace std;
class MyDate
{
public:
void init_date()
{
cout << "year,month,day" << endl;
cin >> year;
cin >> month;
cin >> day;
}
//打印data的接口
void print_data()
{
cout << year << "年" << month << "月" << day << "日" << endl;
}
bool _is_leap_year()
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
return true;
}
return false;
}
private:
int year;
int month;
int day;
};
int main()
{
MyDate my_date;
my_date.init_date();
my_date.print_data();
if (my_date._is_leap_year() == true)
{
cout << "是閏年" << endl;
}
else
{
cout << "不是閏年" << endl;
}
return 0;
}
面向對象和麪向過程
面向過程:函數發生驅動,
面向對象:對象發生驅動
* 面向對象的小練習:
求圓的周長和麪積
數據描述:
半徑,周長,面積均用實型數表示
數據處理:
輸入半徑r;
計算周長 = 2*pi*r;
計算面積 = pi*r*r;
輸出半徑,周長,面積;
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
using namespace std;
//求圓的周長和麪積
class Circle
{
public:
void setR(double r) //設置圓的半徑,因爲從外部不能操作私有成員r
{
m_r = r;
}
double GetR()
{
return m_r;
}
double Get_Perimeter() //得到圓的周長
{
return 2 * 3.14*m_r;
}
double Get_Circlar_Area() //得到圓的面積
{
return 3.14*m_r*m_r;
}
private:
double m_r; //圓的私有成員-半徑
};
int main()
{
Circle c;
c.setR(10);
cout << "圓的半徑是:" << c.GetR() << endl;
cout << "圓的周長是:" << c.Get_Perimeter() << endl;
cout << "圓的半徑是:" << c.Get_Circlar_Area() << endl;
return 0;
}