返回信息流我们都清楚指针和引用的区别,但是谁能解释一下下面的情况:
要通过A的方法CreateB可以创建一个B的对象,并且通过传进来的参数返回B的对象。
可以实现
A::CreateB( B *b );
或者
A::CreateB( B &b );
前者是传指针,后者是传引用,
那么 A::CreateB(B *&b) 是什么意思,他和前面的两个又有什么不同?
我现在的感觉是:
如果C继承自B,即class C :B {...}, 可以实现如下的代码
A::CreateB( B *b ) //如果用这个方法
{...}
A a;
C *c;
a.CreateB(c);
这里对象c会自动向上类型转换成B类型,所以调用a.CreateB(c);没有问题,
但是,
A::CreateB( B *&b ) //如果用这个方法
{...}
A a;
C *c;
a.CreateB(c);
调用a.CreateB(c);的时候编译则通不过。
所以是不是采用 A::CreateB(B *&b)就是为了防止向上类型转换,即传进来的参数必须是B类型的?
请高手解答一下,,谢谢了。
这是一条镜像帖。来源:北邮人论坛 / soft-design / #22423同步于 2007/11/22
该镜像源已超过 30 天没有更新,可能在源站已被删除。
SoftDesign机器人发帖
请教个高级C++问题~
huan23
2007/11/22镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
首先,用指针直接传参进去,然后期望出来能够得到一片内存,是不行的,这个你复习下形参和实参的意义你就知道了,
其次,B *&b表示的是传递一个指针的引用,这样分配的内存才会真正被"返回"
用指针或者引用作为形参,函数运行的时候都不会复制该指针指向的对象。
A::CreateB( B *b ) //如果用这个方法
{...}
A a;
C *c;
a.CreateB(c);
a.CreateB(c); //运行的时候指向c指向对象中的B的部分。
受教
【 在 wakaka007 (拒绝凝结的水) 的大作中提到: 】
: 用指针或者引用作为形参,函数运行的时候都不会复制该指针指向的对象。
: A::CreateB( B *b ) //如果用这个方法
: {...}
: ...................
如果改成A::CreateB(B *const&b)的话,
调用a.CreateB(c);的时候就不会有问题了。
发生隐式类型转换的时候会引入临时变量,
普通引用不能与临时变量进行绑定,
指向常量的引用就不会受到这个限制了。
// Begin
Initialization of a reference is trivial when the initializer is an
lvalue (an object whose address you can take; see §4.9.6). The
initializer for a 'plain' T& must be an lvalue of type T. The
initializer for a const T& need not be an lvalue or even of type T.
In such cases (David''s notes: and only in such cases),
[1] first, implicit type conversion to T is applied if necessary (see §C.6);
[2] then, the resulting value is placed in a temporary variable of type T; and
[3] finally, this temporary variable is used as the value of the initializer.
Consider:
double& dr = 1; // error: lvalue needed
const double& cdr = 1; // ok
The interpretation of this last initialization might be:
double temp = double(1) ; // first create a temporary with the right value
const double& cdr = temp; // then use the temporary as the initializer for cdr
A temporary created to hold a reference initializer persists until
the end of its reference’s scope.
References to variables and references to constants are distinguished
because the introduction of a temporary in the case of the variable
is highly errorprone;
an assignment to the variable would become an assignment to the –
soon to disappear – temporary. No such problem exists for references
to constants, and references to constants are often important as
function arguments (§11.6).
// End