为什么我们不能将*用于复制构造函数,为什么要使用引用? [英] Why can not we use * for copy constructor, why reference is used?
本文介绍了为什么我们不能将*用于复制构造函数,为什么要使用引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hello程序员,
我想知道为什么复制构造函数中仅使用引用,为什么不使用指针?
我使用了指针,得到了理想的结果.
请对此进行一些说明.下面是我编写的代码,我可以看到预期的结果.使用引用时得到的结果相同.
有什么特定的原因不使用指针吗?
Hello Programmers,
I would like to know why only reference is used in copy constructor, why not pointer?
I used pointer, I get perfect result.
Please put some light on this. Below is the code that I wrote, I am able to see expected result. The same result I get when use reference.
Is there any specific reason not to use pointer?
#include "stdafx.h"
#include<iostream>
#include<stdio.h>
using namespace std;
class MyString
{
public:
char *str1;
int i;
MyString(char * , int );
MyString();
MyString (MyString* );
};
MyString::MyString()
{
}
MyString::MyString( char * str2, int j)
{
str1 = str2;
i= j;
}
MyString::MyString (MyString * obj3)
{
int len = strlen(obj3->str1);
str1 = (char*)malloc(len +1);
strcpy( str1, obj3->str1);
i= obj3->i;
}
int _tmain(int argc, _TCHAR* argv[])
{
MyString obj1("HelloWorld", 10);
MyString obj2(&obj1);
cout<<obj2.str1;
cout<<obj2.i;
int j;
cin >>j;
return 0;
}}
问候,
Joy
Regards,
Joy
推荐答案
您的问题可以这样改写:"为什么我们应该使用引用而不是指针?"
您可能会在这里找到原因:"[8.6]什么时候应该使用引用,什么时候应该使用引用指针?" [ ^ ].
请注意此
You question could be rephrased this way: "why should we use references instead of pointers?"
You may find a reason here: "[8.6] When should I use references, and when should I use pointers?"[^].
Please note this
MyString (MyString* );
应该改为
should be instead
MyString (const MyString* );
最佳答案 -
空指针毫无意义.而且使用指针将不允许复制临时对象,因此您将无法执行以下操作:
Best answer, in my opinion -
"A null pointer wouldn''t make sense. And using a pointer wouldn''t allow copying temporaries, so you couldn''t do things like:
MyClass
func()
{
// ...
return MyClass(...);
}
这就是复制构造函数的定义方式.根据定义,您定义的构造函数根本不是复制构造函数.复制构造函数是在您按值将参数传递给函数时被隐式调用的构造函数.由于它是隐式的,因此无法指定采用原始对象的地址.
您可以随意定义一个构造函数,该构造函数将改为使用指针并使它的行为相同.但这不是被隐式调用的.
That''s how the copy constructor is defined. The constructor you defined is, per definition, not a copy constructor at all. The copy constructor is the one that will be implicitely called whenever you pass an argument by value to a function. Since it''s implicit, you can''t specify to take the address of the original object.
You''re free to define a constructor that takes a pointer instead and make it behave the same. But that is not the one that will be called implicitely.
这篇关于为什么我们不能将*用于复制构造函数,为什么要使用引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文