为什么不允许复制构造函数传递值? [英] Why is copy constructor not allowed pass by value?

查看:161
本文介绍了为什么不允许复制构造函数传递值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:



可以将对象作为值传递给副本构造函数


Possible Duplicate:
Why should the copy constructor accept its parameter by reference in C++?
Can a object be passed as value to the copy constructor

考虑这段代码:

class complex{
        private:
                double re, im;
        public:
                complex(double _re, double _im):re(_re),im(_im){}
                complex(complex c):re(c.re),im(c.im){}
};

编译时,我收到一条错误消息:无效的构造函数;你可能的意思是复杂(const complex&)'

When compiled, I got an error message: invalid constructor; you probably meant ‘complex (const complex&)’

C ++编程语言,它写成:


复制构造函数定义了什么复制手段 - 包括
复制参数意味着什么 - 写

The copy constructor defines what copying means – including what copying an argument means – so writing

complex:complex(complex c):re(c.re),im(c.im){} // error

complex : complex(complex c) :re(c.re) , im(c.im) { } // error

是一个错误,因为任何调用都将涉及无限递归。

is an error because any call would have involved an infinite recursion.

为什么会导致无限递归?

Why does this cause infinite recursion? It doesn't make sense.

推荐答案

按值传递表示参数 已复制 。调用复制构造函数。

Passing by value means that the parameter is copied into the function. That calls the copy constructor.

如果你的复制构造函数参数是pass-by-value ...它会一次又一次地调用... ...

If your copy constructor parameter is pass-by-value... It would call itself... over and over again...

这篇关于为什么不允许复制构造函数传递值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆