vendredi 30 décembre 2022

C++ Updating reference variable pointer to another location [duplicate]

Here is my simple code

#include <iostream>
#include <string>

using namespace std;

int main() {
    
    string food = "Pizza";
    string &meal = food;
    
    string okay = "okay";
    
    &meal = okay; // showing error in updating meal reference
    
    cout << food << "\n";  // Outputs should be Pizza
    cout << meal << "\n";  // Outputs Should be okay
    return 0;
}

I reference have a meal variable to the same location as food so now the meal value is Pizza but now I want to update the meal reference location to okay such that the food value is still Pizza but the meal updated to okay.

is there any way to update the reference variable to another variable?

enter image description here

Aucun commentaire:

Enregistrer un commentaire