geeksforgeeks 008-使用引用或指针传递参数的用处

  1. 去修改调用函数的局部变量
  2. 对于传递比较大的参数时

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class Employee {
    private:
    string name;
    string desig;


    };

    void (Employee emp) {
    cout<<emp.getName();
    cout<<emp.getDesig();

    // Print more attributes
    }

    每次调用printEmDetails时,都会创建一个Employee

  3. 为了防止对象切割(Object Slicing)
    多态的实现是靠指针和引用,而对象的转换只能造成对象切割,不能实现多态

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    #include <iostream>
    #include<string>

    using namespace std;

    class Pet {
    public:
    virtual string getDescription() const {
    return "This is Pet class";
    }
    };

    class Dog : public Pet {
    public:
    virtual string getDescription() const {
    return "This is Dog class";
    }
    };

    void describe(Pet p) { // Slices the derived class object
    cout<<p.getDescription()<<endl;
    }

    int main() {
    Dog d;
    describe(d);
    return 0;
    }

    Output:

    1
    This is Pet Class

    修改后

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    #include <iostream>
    #include<string>

    using namespace std;

    class Pet {
    public:
    virtual string getDescription() const {
    return "This is Pet class";
    }
    };

    class Dog : public Pet {
    public:
    virtual string getDescription() const {
    return "This is Dog class";
    }
    };

    void describe(const Pet &p) { // Doesn't slice the derived class object.
    cout<<p.getDescription()<<endl;
    }

    int main() {
    Dog d;
    describe(d);
    return 0;
    }

    Output:

    1
    This is Dog Class
  4. 为了实现函数的运行时多态