ट्रैक
/
C++
C++
/
सिलेबस
/
रेफरेंस
रे

रेफरेंस में C++

1 अभ्यास

रेफरेंस के बारे में

कॉपियाँ और रेफरेंस

अब तक जो हम जानते हैं, उसके हिसाब से किसी फंक्शन की मदद से वेरिएबल की वैल्यू बदलना थोड़ा झंझट भरा है। हर फंक्शन आर्गुमेंट को कॉपी की तरह संभाला जाता है, इसलिए वह मूल वैल्यू को नहीं बदलता। आपके टाइप के आकार के आधार पर यह आपके कोड के परफॉर्मेंस पर गंभीर असर डाल सकता है।

int adjust_salary(int base, int kids) {
    return base + kids * 500;
}
int now_a_mother_of_twins{2500};
adjust_salary(now_a_mother_of_twins, 2);

// now_a_mother_of_twins is still 2500
now_a_mother_of_twins = adjust_salary(now_a_mother_of_twins, 2);
// now_a_mother_of_twins is now 3500

References को उपनाम की तरह देखा जा सकता है; उनमें किए गए बदलाव मूल वेरिएबल पर असर डालते हैं। References टाइप घोषणा में एम्परसैंड (&) का इस्तेमाल करते हैं।

int balance{1000};
int& budget{balance};
int pro_computer_wheels{699};
budget -= pro_computer_wheels;
// budget is now 301;
// balance is also 301;

रेफरेंस को दोबारा बाँधना (एक reference का बंधन बदलना) संभव नहीं है। आपके पास बिना इनिशियलाइज़ किया हुआ reference नहीं हो सकता। References को किसी मौजूदा वेरिएबल के साथ इनिशियलाइज़ करना ज़रूरी है।

int main_acc{1'000'000};
int side_acc{-20};
int& savings{main_acc};
// => main_acc and savings are 1'000'000

// try to reseat savings to use main account
savings = side_acc;
// savings and main_acc are now -20
// as this uses the **value** of side_acc
savings += 20;
// savings and main_acc are now 0, side_acc is stil -20

int& future_budget;
// => compiler error, reference must be bound!

void

references की शक्ति से आपको शायद किसी फंक्शन से कोई वैल्यू लौटाने की ज़रूरत ही न पड़े। इस स्थिति में void को रिटर्न टाइप के रूप में इस्तेमाल किया जाता है।

void increase_power(int& level) {
    level += 500;
}
int goku{8700};
increase_power(goku);
// goku's power level?
// It's over 9000!
GitHub के ज़रिए संपादित करें यह लिंक नई विंडो या टैब में खुलता है।

रेफरेंस सीखिए