1、如何用codeblocks创建一个C++项目:https://jingyan.baidu.com/article/0bc808fc55bfbc1bd585b97f.html
2、类是对某一类对象的抽象,对象是某一种类的实例。
类:一种复杂的数据类型,将不同类型的数据(数据成员)和与这些数据相关的操作(成员函数)封装在一起的集合体。
3、类的定义格式:
class 类名(首字母大写)
{
private:
私有数据成员和成员函数
protected:
保护数据成员和成员函数
public:
公有数据成员和成员函数
};
4、成员函数的实现:
(1)将成员函数的实现放在类的内部(即一对大括号内),使其自动成为内联函数。(成员函数定义的时候顺带实现)(适用于成员函数较少的情况,节省代码量)
(2)在类定义中只给出成员函数的原型,成员函数的实现放在类的外部。(适用于成员函数较多的情况,使看上去不那么凌乱,执行的功能一目了然) (在cpp文件内实现,这种方法是最常用的)
5、(1)cpp和h的分开,cpp写实现,h写声明(也就是接口),这是因为面向对象的核心思想之一就是要求接口与实现的分离。
(2)一个工程入口点是main函数。建立一个工程,里面有很多个cpp,但只能有一个main函数。编译器每次会编译所有的cpp文件,然后把他们链接在一起,成为一个可执行文件。
6、访问属性
private(私有成员):只允许该类的成员函数及友元访问
protected(保护成员): 允许该类的成员的函数及友元访问;允许其派生类的成员函数访问
public(公有成员):允许该类的成员函数访问;允许类外部的其他函数访问
例子:创建一个工程,定义一个日期类。
Date.h
#ifndef DATE_H
#define DATE_H
#include<iostream>
using namespace std;
class Date
{
public: ///定义公有成员函数
Date();///构造函数
virtual ~Date();///析构函数
public: ///声明成员函数
void SetDate(int ,int ,int );
void Display();
int GetYear();
int GetMonth();
int GetDay();
protected:
private:///私有的数据成员
int year;
int month;
int day;
};
#endif // DATE_H
Date.cpp(成员函数的具体实现在这里面进行)
#include "Date.h"
#include<iostream>
using namespace std;
Date::Date()
{
//ctor
}
Date::~Date()
{
//dtor
}
void Date::SetDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
int Date::GetYear()
{
return year;
}
int Date::GetMonth()
{
return month;
}
int Date::GetDay()
{
return day;
}
void Date::Display()
{
cout<<year<<"-"<<month<<"-"<<day<<endl;
}
main.cpp(一个工程只能有一个main.cpp)
#include <iostream>
#include"Date.h"
using namespace std;
int main()
{
Date today,*t;///创建一个Date类的对象,和指向对象的指针(只能存储对象的地址)
today.SetDate(2019,9,28);///通过对象以圆点形式访问成员函数
cout<<"One day is ";
today.Display();
t=&today;///
(*t).SetDate(2020,3,1);
cout<<"the other day is ";
(*t).Display();
t->SetDate(2021,10,4);///通过指针以箭头的形式访问成员函数
cout<<"the other day is ";
t->Display();
return 0;
}
7、this指针
提出问题:成员函数为该类的所有对象所共享,成员函数如何辨别出当前调用自己的是哪个对象呢?
定义:类中的每个成员函数都有一个特殊的隐含指针,称为this指针,用来存放当前调用该函数的对象的地址
过程:系统将当前调用成员函数的对象的地址赋值给this指针,成员函数就能通过this指针指向的位置来读取当期对象的数据成员信息。
例子:创建Date类的两个对象,验证this指针的作用
Date.cpp(实现Date.h中成员函数的文件)
#include "Date.h"
#include<iostream>
using namespace std;
Date::Date()
{
//ctor
}
Date::~Date()
{
//dtor
}
void Date::SetDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void Date::Display()
{
cout<<"调用该函数的对象的地址保存在Display()函数的this指针中,为";
cout<<this<<endl;
cout<<"当前对象中year成员的起始地址:";
cout<<&(this->year)<<endl;///&为取地址符,取出当前对象中year成员的地址,注意this->year是一体的
cout<<"当前对象中的month成员的起始地址:";
cout<<&(this->month)<<endl;
cout<<"year="<<this->year<<",month="<<this->month<<endl;
}
main.cpp
#include <iostream>
#include"Date.h"
using namespace std;
int main()
{
Date DateA,DateB;
DateA.SetDate(2011,7,24);
DateB.SetDate(2010,10,4);
cout<<"DateA地址"<<&DateA<<endl;///输出对象DateA的地址
DateA.Display(); ///对象DateA调用成员函数void Display(),先把DateA的地址赋给Display()函数的this指针
cout<<"DateB地址"<<&DateB<<endl;
DateB.Display();
return 0;
}