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

后端 未结 5 1981
离开以前
离开以前 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:34

    If you want to pass class instances (objects), you either use

     void function(const MyClass& object){
       // do something with object  
     }
    

    or

     void process(MyClass& object_to_be_changed){
       // change member variables  
     }
    

    On the other hand if you want to "pass" the class itself

    template
    void function_taking_class(){
       // use static functions of AnyClass
       AnyClass::count_instances();
       // or create an object of AnyClass and use it
       AnyClass object;
       object.member = value;
    }
    // call it as 
    function_taking_class();
    // or 
    function_taking_class();
    

    with

    class MyClass{
      int member;
      //...
    };
    MyClass object1;
    

提交回复
热议问题