How to use a class object in C++ as a function parameter

后端 未结 5 1902
离开以前
离开以前 2021-01-30 07:15

I am not sure how to have a function that receives a class object as a parameter. Any help? Here is an example below.

#include

void function(cla         


        
5条回答
  •  旧巷少年郎
    2021-01-30 07:56

    At its simplest:

    #include 
    using namespace std;
    
    class A {
       public:
         A( int x ) : n( x ){}
         void print() { cout << n << endl; }
       private:
         int n;
    };
    
    void func( A p ) {
       p.print();
    }
    
    int main () {
       A a;
       func ( a );
    }
    

    Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.

提交回复
热议问题