C++|帶參數的構造函數


基礎語法而已。

#include <iostream>
using namespace std;

class Demo
{
    public:
        Demo()
        {
            x = 0;
            cout << "Demo 的默認構造函數!" << x << endl;
        }
        Demo(int i)
        {
            x = i;
            cout << "Demo 的帶一個參數的構造函數!!" << x << endl;
        }
        ~Demo()
        {
            cout << "Demo 的析構函數!" << x << endl;

        }
        int get_x()
        {
            return x;
        }
        void set_x(int i)
        {
            x = i;
        }
    private:
        int x;
};

class Rectangle
{
    public:
        Rectangle()
        {
            x = 1000;
            cout << "Rectangle 的默認構造函數!" << x << endl;
        }
        Rectangle(int i, int j, int k):x(i), width(j), length(k)
        {
           cout << "Rectangle 的帶三個參數的構造函數!" <<   "長方形的面積 b 為:" << length.get_x() * width.get_x() << endl;
        }
        ~Rectangle()
        {
            cout << "Rectangle 的默認析構函數!" << x << endl;
        }
        int area()
        {
            return length.get_x() * width.get_x();
        }
    private:
        Demo length;
        Demo width;
        int x;
};

int main()
{
    Rectangle rec(100, 200, 300);

    cout << "\n=========\n" << endl;

    Rectangle *rec1 = new Rectangle(100, 200, 300);
    delete rec1;

    return 0;
}

輸出:

Demo 的帶一個參數的構造函數!!300
Demo 的帶一個參數的構造函數!!200
Rectangle 的帶三個參數的構造函數!長方形的面積 b 為:60000

=========

Demo 的帶一個參數的構造函數!!300
Demo 的帶一個參數的構造函數!!200
Rectangle 的帶三個參數的構造函數!長方形的面積 b 為:60000
Rectangle 的默認析構函數!100
Demo 的析構函數!200
Demo 的析構函數!300
Rectangle 的默認析構函數!100
Demo 的析構函數!200
Demo 的析構函數!300 

參考:《范磊:C++》P153


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM