复制构造函数传引用

#include "stdafx.h"

#include <iostream>

 

class A

{
 
private:
 
 int value;
 
public:
 
 A(int n)
  
 {
  
  value = n;
  
 }
 
 
 
 A(const A &y)//此处只能传引用,传指针,传值都是要造成无限调用构造函数的。
  
 {
  
  value = y.value+10;
  
 }
 
 
 
 void Print()
  
 {
  
  std::cout << value << std::endl;
  
 }
 
};


int main(int argc, char* argv[])
{
 A a = 10;
 
 A b = a;
 
 b.Print();//输出20
 a.Print();//输出10
 return 0;
}

拷贝构造函数是一种特殊的构造函数,在创建一个新对象时,它会从另一个已存在的对象中复制构造函数参数。其函数原型为: ``` 类名(const 类名 &obj) ``` 其中,参数列表中的 "const" 关键字表示输入参数为只读, "&" 符号表示递的是引用类型,即万一进来的是个 reference ,就不会产生歧义。 以下是一个拷贝构造函数的示例代码: ``` #include <iostream> using namespace std; class Box { public: // 通常的构造函数 Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } // 拷贝构造函数 Box(const Box &B) { cout << "Copy constructor called." << endl; length = B.length; breadth = B.breadth; height = B.height; } double Volume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main() { Box Box1(3.3, 1.2, 1.5); //声明对象时调用了通常的构造函数 Box Box2(Box1); //声明对象时调用了拷贝构造函数 // 输出 Box1 的体积 cout << "Box1 的体积:" << Box1.Volume() << endl; // 输出 Box2 的体积 cout << "Box2 的体积:" << Box2.Volume() << endl; return 0; } ``` 在上面的代码中,我们声明了一个 Box 类,并声明了一个常用的构造函数和一个拷贝构造函数。这里的 Box1 对象调用了常用的构造函数,而 Box2 对象则在声明时调用了拷贝构造函数。最后,通过 Volume() 函数计算 Box1 和 Box2 对象的体积并输出。 希望这个示例能帮助你理解拷贝构造函数的概念。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ysgs129

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值