C++(三)——类和对象(上)
生活随笔
收集整理的這篇文章主要介紹了
C++(三)——类和对象(上)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
構造函數
#include<iostream> using namespace std;class Person { public:int age;Person() {cout << "無參構造" << endl;}Person(int a) {age = a;cout << "有參構造" << endl;}//拷貝構造參數Person(const Person &p) {age = p.age;cout << "拷貝構造" << endl;}~Person() {cout << "析構函數" << endl;}}; int main1() { // Person p1;//無參構造 // Person p2(10);//有參構造 // Person p3(p2);//拷貝構造//cout << "p2的age=" << p2.age << endl;//cout << "p3的age=" << p3.age << endl;//調用默認構造函數時不加()//2.顯示法Person p1;Person p2 = Person(15);Person p3 = Person(p2);//注意事項,不要利用拷貝構造函數來初始化一個匿名對象, 編譯器會認為是對象的聲明//Person(p3);//3.隱式轉換法//Person p4 = 10; ////Person p5 = p4;return 0; }深拷貝與淺拷貝
#include<iostream> using namespace std; class Person { public:int m_age;int* m_height;Person() {cout << "無參構造" << endl;}Person(int age, int height) {m_age = age;m_height = new int(height);cout << "有參構造" << endl;}//省略此步即為淺拷貝,編譯器默認的拷貝構造函數為淺拷貝,析構時會重復釋放指針導致報錯//Person(const Person &p) {// m_age = p.m_age;// m_height = new int(*p.m_height);// cout << "拷貝構造" << endl;//}~Person() {if (m_height != NULL) {delete(m_height);m_height = NULL;}cout << "析構函數" << endl;}}; void testG() {Person p1(15, 177);Person p2(p1);cout << "p1的age = " << p1.m_age << " p1的height = " << *p1.m_height<< endl;cout << "p2的age = " << p2.m_age << " p2的height = " << *p2.m_height<< endl;} int main() {testG();return 0;}對象特性——初始化列表
#include<iostream> using namespace std; class Person { public:int m_a;int m_b;int m_c;Person(int a, int b, int c) :m_a(a), m_b(b), m_c(c) {}}; void test() {Person p(15, 25, 0);cout << p.m_a << endl;cout << p.m_b << endl;cout << p.m_c << endl;}int main() {test();}類對象作成員
#include<iostream> using namespace std; class Phone { public:string m_phoneName;Phone(string phoneName) {m_phoneName = phoneName;cout << "構造phone" << endl;}~Phone() {cout << "析構phone" << endl;} };class Person { public:Phone m_p;string m_name;Person(string phoneName, string name) :m_p(phoneName), m_name(name){cout << "構造person" << endl;}~Person() {cout << "析構person" << endl;} };void test() {Person p("iPhone", "motherfucker");cout << p.m_p.m_phoneName << endl;cout << p.m_name << endl;};int main() {test();return 0; } //打印結果,注意先構造對象成員,析構時順序相反//構造phone //構造person //iPhone //motherfucker //析構person //析構phone靜態成員——靜態函數
#include<iostream> using namespace std; class Person { public:int m_b;static void func() {cout << "調用靜態函數" << endl;s_a = 100;//m_b = 0;靜態成員函數只能訪問靜態變量,不能訪問成員變量} private:static int s_a;}; int Person::s_a = 0; void test() {Person p;p.func();Person::func; }int main() {test();return 0; }成員變量與成員函數分開存儲
#include<iostream> using namespace std; //成員變量和成員函數分開存儲 class Person {int m_A;//非靜態成員變量 屬于類的對象上static int m_b;//靜態的成員變量與成員函數 不屬于類的對象上void func(){}//非靜態 不屬于類的對象上}; void test01() {Person p;//空對象占用空間1個字節//c++編譯器給空對象分配一個字節空間,是為了區分空對象占用的位置//每個空對象都有一個獨一無二的內存地址cout << "size of p = " << sizeof(p) << endl; } int main() {test01(); }總結
以上是生活随笔為你收集整理的C++(三)——类和对象(上)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: numpy学习记录
- 下一篇: C++(四)——类和对象(下)