類是創建對象的模板,不占用內存空間,不存在於編譯后的可執行文件中。
對象是實實在在的數據,需要內存來存儲,對象被創建時會在棧區或者堆區分配內存。

#include<iostream>
#include<string>
using namespace std;
class Student{
private:
string m_name;
int m_age;
float m_score;
public:
void setname(string name);
void setage(int age);
void setscore(float score);
void show();
};
void Student::setname(string name){
m_name = name;
}
void Student::setage(int age){
m_age = age;
}
void Student::setscore(float score){
m_score = score;
}
void Student::show(){
cout<<m_name<<"的年齡是"<<m_age<<",成績是"<<m_score<<endl;
}
int main(){
//在棧上創建對象
Student stu;
cout<<sizeof(stu)<<endl;
//在堆上創建對象
Student *pstu = new Student();
cout<<sizeof(*pstu)<<endl;
//類的大小
cout<<sizeof(Student)<<endl;
return 0;
}
/*運行結果*/
16 //string占8個字節、int和float都占4個字節 = 16字節
16 //說明對象所占的內存僅僅包含了成員變量
16 //計算類的大小時,只計算了成員變量的大小,並沒有把成員函數包含在內
成員函數的調用
成員函數最終被編譯成與對象無關的全局函數,成員變量的作用域不是全局,如果成員函數中使用到了成員變量怎么辦?
C++規定,編譯成員函數時要額外添加一個參數,把當前對象的指針傳遞進去,通過指針來訪問成員變量。
通過傳遞對象指針完成了成員函數和成員變量的關聯。這與我們表面看到的剛好相反,通過對象調用成員函數時,不是通過對象找函數,而是通過函數找對象。這一切都是隱式完成的,對程序員來說完全透明,就好像這個額外的參數不存在一樣。
