C++

12166 ワード

Call by reference


関数を呼び出す方法は3つあります.
  • 按値呼:按値転送
  • 呼按アドレス:按アドレス転送(ex.Pointer)
  • 参照コール:参照転送
  • Call by referenceの例を次に示します.
    #include <iostream>
    
    class Person {
     public:
      Person(const std::string &name, int age);
      
      std::string get_name() { return this->name; }
      int get_age() { return this->age; }
      void change_name(const std::string &name) { this->name = name; }
      void change_age(int age) { this->age = age; }
    
     private:
      std::string name;
      int age;
    };
    
    Person::Person(const std::string &name, int age) {
      this->name = name;
      this->age = age;
    }
    
    void changeInfo(Person &p1, Person &p2) {
      Person p3 = p1;
      
      std::cout << "[changeInfo before] p1's info         : ["
        << p1.get_name() << ", " << p1.get_age() << "], p2's info   : ["
        << p2.get_name() << ", " << p2.get_age() << "]" << std::endl;
      
      p1 = p2;
      p2 = p3;
    
      std::cout << "[changeInfo after]  p1's info         : ["
        << p1.get_name() << ", " << p1.get_age() << "],       p2's info   : ["
        << p2.get_name() << ", " << p2.get_age() << "]" << std::endl;
    }
    
    int main() {
      Person guitarggun("guitarggun", 29);
      Person john("john", 20);
      
      std::cout << "[before]            guitarggun's info : ["
        << guitarggun.get_name() << ", " << guitarggun.get_age()
        << "], john's info : [" << john.get_name() << ", " << john.get_age() << "]"
        << std::endl;
      
      changeInfo(guitarggun, john);
      
      std::cout << "[after]             guitarggun's info : ["
        << guitarggun.get_name() << ", " << guitarggun.get_age()
        << "],       john's info : [" << john.get_name() << ", " << john.get_age()
        << "]" << std::endl;
      
      return 0;
    }

    C++はこれで終わります.