在C++中,变量由于引用原因而被传递: 1) 要修改调用者函数的局部变量,请执行以下操作: 引用(或指针)允许被调用函数修改调用函数的局部变量。例如,考虑下面的示例程序 乐趣 能够修改局部变量 十、 属于 main() .
CPP
#include <bits/stdc++.h> using namespace std; void fun( int & x) { x = 20; } int main() { int x = 10; fun(x); cout << "New value of x is " << x; return 0; } |
输出: x的新值是20 2) 对于传递大型参数: 如果参数很大,则通过引用(或指针)传递会更有效,因为只传递一个地址,而不是整个对象。例如,让我们考虑以下问题 受雇者 类和函数 printEmpDetails() 打印员工详细信息。
C
class Employee { private : string name; string desig; // More attributes and operations }; void printEmpDetails(Employee emp) { cout << emp.getName(); cout << emp.getDesig(); // Print more attributes } |
以上代码的问题是:每次 printEmpDetails() 调用时,将构造一个新的Employee对象,该对象涉及创建所有数据成员的副本。因此,更好的实现方式是将员工作为参考。
C
void printEmpDetails( const Employee& emp) { cout << emp.getName(); cout << emp.getDesig(); // Print more attributes } |
这一点仅适用于结构和类变量,因为对于int、char等基本类型,我们没有任何效率优势。 3) 要避免对象切片,请执行以下操作: 如果我们将子类的对象传递给一个需要超类对象的函数,那么传递的对象就是 切片 如果它是通过值传递的。例如,考虑下面的程序,它打印“这是宠物类”。
C
#include <iostream> 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() << '' ; } int main() { Dog d; describe(d); return 0; } |
输出: 这是宠物课 如果我们在上面的程序中使用pass by reference,那么它会正确地打印“This is Dog Class”。请参阅下面修改的程序。
C++
#include <iostream> 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() << '' ; } int main() { Dog d; describe(d); return 0; } |
输出: 这是狗课 这一点对于int、char等基本数据类型也无效。 4) 在函数中实现运行时多态性 通过将对象作为引用(或指针)传递给函数,我们可以使函数具有多态性。例如,在下面的程序中,print()接收对基类对象的引用。如果传递了基类对象,函数print()调用基类函数show(),如果传递了派生类对象,函数show()调用派生类函数show()。
C++
#include <iostream> using namespace std; class base { public : virtual void show() { // Note the virtual keyword here cout << "In base" ; } }; class derived : public base { public : void show() { cout << "In derived" ; } }; // Since we pass b as reference, we achieve run time // polymorphism here. void print(base& b) { b.show(); } int main( void ) { base b; derived d; print(b); print(d); return 0; } |
输出: 在基地 派生的 幸亏 文基 谢谢你补充这一点。 作为旁注,如果引用参数仅由于上述第2或第3条原因而通过引用传递,则建议将引用参数设置为常量。建议这样做,以避免对对象进行意外修改。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。