特徵:抽象-封裝-繼承-多態函數
class 類名 { private: 私有成員(本類) public: 公共成員(全部) protected: 保護成員(繼承類) }
class 結構體名 { private: 私有成員(本類) public: 公共成員(全部) protected: 保護成員(繼承類) }
union 聯合體名 { private: 私有成員(本類) public: 公共成員(全部) protected: 保護成員(繼承類) }
enum class 枚舉類型名:類型 { 枚舉1,枚舉2...枚舉n }
class Demo { public: //默認生成空函數體的構造器 //若自定義構造器,系統再也不生成默認構造器 //若要系統生成默認構造器,指明便可 Demo()=default; Demo(int x,int y); private: int x,y; }
Demo(int x,int y) { this->x=0; this->y=0; } Demo():x(0),y(0){}
Demo():Demo(0,0){}
調用複製構造器的狀況:
1.以本類對象初始化新對象
2.實參初始化形參
3.return類的對象this
class Point { private: int x, y; public: Point():x(0),y(0){} Point(int x, int y); Point(const Point& p); }; Point::Point(int x, int y) { this->x = x; this->y = y; } Point::Point(const Point& p) { this->x = p.x; this->y = p.y; cout << "複製構造函數運行中..." << endl; }
class Point { ~Point(); }
局部做用域:形參和代碼塊中的標識符
類做用域:類內成員
靜態生存期:與程序運行期相同(static變量)
動態生存期:從聲明開始到做用域結束code
構造構造器初始化表(按成員變量在類中的定義順序)
執行構造器體對象
class 類名;繼承
friend double view(const Point &p1,const Point &p2) { double x = p1.x - p2.x; double y = p1.y - p2.y; return sqrt(x * x + y * y); }
class A { friend class B; public: void view() { cout << x << endl; } private: int x; }; class B { public: void set(int i) { a.x = 1; } void view() { a.view(); } private: A a; };