C++建構函式

來源:互聯網
上載者:User

標籤:

 
  1. #include <iostream>
  2. using namespace std;
  3. class ClassTest
  4. {
  5. public:
  6. ClassTest()
  7. {
  8. cout << "ClassTest()" <<endl;
  9. }
  10. ClassTest(int i)
  11. {
  12. cout << "ClassTest(int)" <<endl;
  13. value2 = i;
  14. }
  15. ClassTest(int i, int j): value(i), value2(j)
  16. {
  17. cout << "ClassTest(int, int)" <<endl;
  18. }
  19. private:
  20. int value = 0;
  21. int value2 = 0;
  22. };
  • 上面是類的聲明與實現,接下來我們來定義類對象。
 
  1. int main()
  2. {
  3. ClassTest test;//使用預設建構函式(即ClassTest())
  4. //ClassTest test();/*這裡被認為是一個函數的聲明,而不是定義對象*/
  5. ClassTest test1(1);//ClassTest(int)
  6. ClassTest test2(1, 2);//ClassTest(int, int)
  7. ClassTest test3 = ClassTest(); //先調用ClassTest()構建一個臨時變數,然後將這個臨時變數通過拷貝建構函式賦值給test3
  8. return 0;
  9. }
  • 定義類指標(引用這裡不再說明)
 
  1. int main()
  2. {
  3. ClassTest * pClass = new ClassTest;
  4. ClassTest * pClass1 = new ClassTest();
  5. ClassTest * pClass2 = new ClassTest(1);
  6. ClassTest * pClass3 = new ClassTest(1, 2);
  7. delete pClass;
  8. delete pClass1;
  9. delete pClass2;
  10. delete pclass3;
  11. return 0;
  12. }
  • 其中第一句和第二句是等價的,它們調用的是同一個建構函式。



來自為知筆記(Wiz)

C++建構函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.