객체의 동적 초기화는 런타임에 객체를 초기화하는 것을 의미합니다. 즉, 객체의 초기 값은 런타임 중에 제공되어야 합니다. 생성자를 사용하고 매개변수 값을 생성자에 전달하여 동적 초기화를 수행할 수 있습니다. 런타임 동안 클래스 변수를 초기화하려면 이러한 유형의 초기화가 필요합니다.
동적 초기화가 필요한 이유는 무엇입니까?
개체의 동적 초기화는 다음과 같이 필요합니다.
-
메모리를 효율적으로 활용합니다.
-
오버로드된 생성자를 사용하여 다양한 초기화 형식을 제공할 수 있습니다.
-
상황을 고려하여 런타임에 다양한 형식의 데이터를 사용할 수 있는 유연성이 있습니다.
예시 코드
#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