希望暴露public
希望隱藏private
對象實例化有兩種方式,從棧實例化,從堆(new出來的)實例化。
以誰做什么作為核心。
public 放前面,private放后面(屬性可以定義為private格式)。
只讀屬性,只有get方法,沒有set方法。
#include <iostream>
#include <string>
using namespace std;
/**
* 定義類:Student
* 數據成員:m_strName
* 數據成員的封裝函數:setName()、getName()
*/
class Student
{
public:
// 定義數據成員封裝函數setName()
void setName(string name) {
m_strName = name;
}
// 定義數據成員封裝函數getName()
string getName() {
return m_strName;
}
//定義Student類私有數據成員m_strName
private:
string m_strName;
};
int main()
{
// 使用new關鍵字,實例化對象
Student *str = new Student;
// 設置對象的數據成員
str->setName("cpp");
// 使用cout打印對象str的數據成員
cout << str->getName() << endl;
// 將對象str的內存釋放,並將其置空
delete str;
str = NULL;
return 0;
}
棧區,存儲變量。
new分配的內存,是堆區。
全局區,存儲全局變量和靜態變量。
常量區,存儲常量。
代碼區,存儲代碼。
對象需要初始化,有的只有一次,有的需要初始化多次。
構造函數,會在對象實例化時被調用。
讀書,視頻,先看思想,讀其骨架。細節次之。
都有默認值的構造函數,稱為默認構造函數。
一個類可以沒有默認構造函數,有別的構造函數也可以實例化對象。
可以全屏觀看,看到關鍵點可以暫停,記錄一下。因為屏幕太小,看着眼疼。或者全屏觀看的時候,把文本置頂。
C++中,構造函數與類名相同,析構函數前面加一個波浪線。析構函數,可以進行資源釋放。
tips:class 聲明類,要小寫的c。構造函數,析構函數前面,不需要任何修飾。class結尾還需要分號;
#include <iostream>
#include <string>
using namespace std;
/**
* 定義類:Student
* 數據成員:m_strName
* 無參構造函數:Student()
* 有參構造函數:Student(string _name)
* 拷貝構造函數:Student(const Student& stu)
* 析構函數:~Student()
* 數據成員函數:setName(string _name)、getName()
*/
class Student
{
public:
Student() {
m_strName = "jack";
cout<<"Student()"<<endl;
}
Student(string _name) {
m_strName = _name;
cout<<"Student(string _name)"<<endl;
}
Student(const Student& stu) {
cout<<"Student(const Student& stu)"<<endl;
}
~Student() {
cout<<"~Student()"<<endl;
}
void setName(string _name) {
m_strName = _name;
}
string getName() {
return m_strName;
}
private:
string m_strName;
};
int main(void)
{
// 通過new方式實例化對象*stu
Student *stu = new Student("小李");
// 更改對象的數據成員為“慕課網”
stu->setName("慕課網");
// 打印對象的數據成員
cout<<stu->getName()<<endl;
delete stu;
stu = NULL;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
/**
* 定義類:Student
* 數據成員:m_strName
* 無參構造函數:Student()
* 有參構造函數:Student(string _name)
* 拷貝構造函數:Student(const Student& stu)
* 析構函數:~Student()
* 數據成員函數:setName(string _name)、getName()
*/
class Student
{
public:
Student() {
m_strName = "jack";
cout<<"Student()"<<endl;
}
Student(string _name) {
m_strName = _name;
cout<<"Student(string _name)"<<endl;
}
Student(const Student &stu) {
cout<<"Student(const Student &stu)"<<endl;
}
~Student() {
cout<<"~Student()"<<endl;
}
void setName(string _name) {
m_strName = _name;
}
string getName() {
return m_strName;
}
private:
string m_strName;
};
int main(void)
{
// 通過new方式實例化對象*stu
Student stu;
Student stu2 = stu;
// 更改對象的數據成員為“慕課網”
stu.setName("慕課網");
// 打印對象的數據成員
cout<<stu.getName()<<endl;
return 0;
}
Student()
Student(const Student &stu)
慕課網
~Student()
~Student()