How to pass objects to functions in C++?

后端 未结 7 883
無奈伤痛
無奈伤痛 2020-11-21 04:55

I am new to C++ programming, but I have experience in Java. I need guidance on how to pass objects to functions in C++.

Do I need to pass pointers, references, or no

相关标签:
7条回答
  • 2020-11-21 05:23

    The following are the ways to pass a arguments/parameters to function in C++.

    1. by value.

    // passing parameters by value . . .
    
    void foo(int x) 
    {
        x = 6;  
    }
    

    2. by reference.

    // passing parameters by reference . . .
    
    void foo(const int &x) // x is a const reference
    {
        x = 6;  
    }
    
    // passing parameters by const reference . . .
    
    void foo(const int &x) // x is a const reference
    {
        x = 6;  // compile error: a const reference cannot have its value changed!
    }
    

    3. by object.

    class abc
    {
        display()
        {
            cout<<"Class abc";
        }
    }
    
    
    // pass object by value
    void show(abc S)
    {
        cout<<S.display();
    }
    
    // pass object by reference
    void show(abc& S)
    {
        cout<<S.display();
    }
    
    0 讨论(0)
提交回复
热议问题