Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Dynamic Initialization ของตัวแปรใน C++

Dynamic initialization ของออบเจ็กต์หมายถึงการเริ่มต้นออบเจ็กต์ขณะรันโปรแกรม (run time) ค่าเริ่มต้นของออบเจ็กต์ถูกกำหนดระหว่างรันโปรแกรม สามารถทำได้โดยใช้ constructors และส่งค่าพารามิเตอร์ไปยัง constructors การเริ่มต้นแบบนี้จำเป็นสำหรับเริ่มต้นตัวแปรของคลาสระหว่างรันไทม์

ทำไมต้องการ dynamic initialization?

  • ใช้หน่วยความจำอย่างมีประสิทธิภาพ
  • ให้รูปแบบการเริ่มต้นต่างๆ ได้ผ่าน overloaded constructors
  • มีความยืดหยุ่นใช้รูปแบบข้อมูลต่างๆ ตามสถานการณ์ขณะรัน

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

class simple_interest {
    float principle, time, rate, interest;
public:
    simple_interest(float a, float b, float c) {
        principle = a;
        time = b;
        rate = c;
    }
    void display() {
        interest = (principle * rate * time) / 100;
        cout << "interest = " << interest;
    }
};

int main() {
    float p, r, t;
    cout << "principle amount, time and rate" << endl;
    cout << "2000 7.5 2" << endl;
    simple_interest s1(2000, 7.5, 2); // dynamic initialization
    s1.display();
    return 1;
}

ผลลัพธ์

Enter principle amount ,rate and time
2000 7.5 2
Interest = 300