我们可以使用指针变量初始化引用变量吗? [英] Can we initialize a reference variable with a pointer variable?

查看:75
本文介绍了我们可以使用指针变量初始化引用变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
class Base
{
    public:
        int a;
        Base():a(0){};
        Base(int x):a(x){};
        void geta(){
            cout<<"a="<<a<<endl;
        }
};
int main()
{
    Base b1(5);
    Base *b3 = &b1;
    Base &b2 = *b3;   //Is it okay?
    b2.geta();
    b3->geta();
    Base b4(10);
    b3 =  &b4;
    b2.geta();
    b3->geta();   
    return 0;
}





我的尝试:



以上代码编译并提供所需的输出。

输出:

a = 5

a = 5

a = 5

a = 10

我的问题:

1.我们可以用指针变量初始化一个引用变量吗?

2.如果允许使用指针初始化引用变量,则在打印b2.geta()时;和

b3-> geta();第二次,两者都应该给出相同的价值。为什么他们不同?



What I have tried:

The above Code compiles and gives desired output.
Output:
a=5
a=5
a=5
a=10
My questions:
1. Can we initialize a reference variable with a pointer variable?
2. If initializing of reference variable with pointer is allowed then when printing b2.geta(); and
b3->geta(); for the second time then both should have given the same value. Why they are different?

推荐答案

你的问题是:
Quote:

我们可以吗?使用指针变量初始化引用变量?

Can we initialize a reference variable with a pointer variable?



我们可以:您的代码演示了这一点。

下一步是


Yes we can: your code demonstrates that.
The next thing is "

Quote:

两者都应该给出相同的值。为什么它们不同?

both should have given the same value. Why they are different?





输出这是我们使用指针的原因。指针 - C ++教程 [ ^ ]



The output is correct. This is actually why we use pointers. Pointers - C++ Tutorials[^]

int main()
{
	Base b1(5);
	Base *b3 = &b1;   // Create pointer b3 and set to point to b1 b3->a==5
	Base &b2 = *b3;   // Create reference b2 and inititialize to whatever b3 points to which is b1 
	// NOTE at this line *b3 dereferences b3 which results in b1. If b3 did not point to a valid object (eg b3==NULL) this would cause the next line to fail at runtime

	b2.geta();
	b3->geta();

	Base b4(10);
	b3 = &b4;         // Now point b3 to b4 b3->a == 10
	cout << "a=" << b3->a << endl;
	b2.geta();
	b3->geta();
	return 0;
}





您将指针b3设置为指向b1,但稍后将其设置为指向b4。因此输出是正确的。

您可以查看使用debubugger发生的事情。



You set the pointer b3 to point to b1 but later you set it to point to b4. Thus the output is correct.
You can view what happens using your debubugger.


这篇关于我们可以使用指针变量初始化引用变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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