1.類的構造函數
定義一個空類 類名爲Test
class Test {
public: //公有成員
protected: //保護成員
private: //私有成員
};
類添加構造函數,因爲正常來說類都是獨立的 所以規範寫到.h及.cpp文件中去
Test.h
#pragma once
#ifndef _TEST_
#define _TEST_
class Test {
public:
Test();
Test(int a, int b);
private:
int X; //正確定義
int Y{0}; //錯誤定義
};
#endif
Test.cpp
#include "stdafx.h"
#include "Test.h"
Test::Test() {};
Test::Test(int a, int b) {
X = a;
Y = b;
}
綜上 我們就按照規範添加好了構造函數 因爲類定義不佔數據空間 如果像定義類變量***Y{0}***的話就會佔用數據空間相矛盾 所以類變量不能初始化 只能通過構造函數初始化 構造函數使用規則如下:
int main()
{
Test t(1,2);
return 0;
}
其中還有構造函數還有多種寫法
在cpp中帶參構造函數
Test::Test(int a, int b) {
X = a;
Y = b;
}
等同於
Test::Test(int a, int b):X(a),Y(b) {
}
也可以在h文件中
class Test {
public:
Test();
Test(int a, int b);
private:
int X;
int Y;
};
等同於
class Test {
public:
Test() {};
Test(int a, int b) {};
private:
int X;
int Y;
};
這樣寫爲內聯後 cpp文件裏就不需要添加構造函數了 注意的是 如果用到遞歸則不能使用這樣的構造函數
當類的成員變量是類對象的時候,我們所有的訪問只能寫成公有的,或者寫出get函數方法,如下類TestOne的類成員變量是Test對象,所以我們訪問T的時候得寫成Public公有的,訪問Test類成員變量得寫出GetA的方法
class Test {
public:
Test() {};
Test(int a, int b):X(a),Y(b) {};
int GetA() {
return X;
}
private:
int X;
int Y;
};
class TestOne {
public:
TestOne(Test t):T(t) {};
public:
Test T;
};
main函數具體的操作是
先構造Test 的t對象 在用具體的t對象構造TestOne對象 最終的訪問都只能訪問public成員
int main()
{
Test t(1,2);
TestOne test(t);
cout << test.T.GetA() << endl;
return 0;
}