C++ References and Java References

后端 未结 4 1521
忘了有多久
忘了有多久 2020-12-30 08:06

//C++ Example

#include 
using namespace std;

int doHello (std::string&);
int main() {
    std::string str1 = \"perry\";
    cout <<         


        
4条回答
  •  温柔的废话
    2020-12-30 08:24

    The code you have written in java is equivalent to this C++ code:

    int main() {
        std::string *s1;
        s1 = new std::string("perry");
        std::cout << s1->c_str() << std::endl;
        doMojo( s1 );
        std::cout << s1->c_str() << std::endl; // not pieterson
    }
    void doMojo( std::string *str ) {
        str = new std::string("pieterson");
        std::cout << str->c_str() << std::end;
    }
    

    perhaps now you see what happens. The C++ references actually wrap around the pointers.. so without the references your code would look like this:

    int main() {
        std::string *s1;
        s1 = new std::string("perry");
        std::cout << s1->c_str() << std::endl;
        doMojo( s1 );
        std::cout << s1->c_str() << std::endl; // now pieterson!
    }
    void doMojo( std::string *&str ) {
        str = new std::string("pieterson");
        std::cout << str->c_str() << std::end;
    }
    

    notice the innocuous ampersand:

    void doMojo( std::string *&str ) {
    

    That really is the secret. This, and the previous answer that explains about immutability of java strings should make you appretiate the difference between java and c++ references.

    Cheers,

    jrh.

提交回复
热议问题