Why could I initialize a string with a direct initialization but not with a reference?

0

Because I can initialize a string with a direct initialization

string tentative("TENTATIVE");
string motAffiche = tentative;

but not with a reference

string tentative("TENTATIVE");
string motAffiche = tentative;

Indeed, gedit tells me that

  

error: conversion from 'std :: __ cxx11 :: string * {aka   std :: __ cxx11 :: basic_string *} 'to non-scalar type   'Std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string}'   requested

Is it as if motAffiche and tentative have the same object, no?

    
asked by ThePassenger 14.03.2017 в 02:21
source

1 answer

0

I guess in your original code you really mean this

int main(int argc, char *argv[])
{
    string tentative("TENTATIVE");
    string motAffiche = &tentative;

    return 0;
}

It actually returns an error because you are trying to assign the address of the string object called tentative to a variable of type string which is incompatible since the variable motAffiche should be a pointer to string.

I suppose that in your question you refer to the c ++ references and not to simple pointers, so one way to achieve what you want would be like this.

int main(int argc, char *argv[])
{
    string tentative("TENTATIVE");
    string& motAffiche = tentative;

    cout<<tentative<<endl;
    cout<<motAffiche<<endl;

    cout<<&motAffiche<<endl;
    cout<<&tentative<<endl;



    return 0;
}

In the example the last two "cout" print the memory addresses of the objects which should be the same since in the second variable we are referring to the first one.

    
answered by 15.03.2017 в 03:50