如何初始化一个类的引用成员变量? [英] How to initialize the reference member variable of a class?

查看:451
本文介绍了如何初始化一个类的引用成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码C ++:

Consider the following code C++:

    #include<iostream>

using namespace std;

class Test {
    int &t;
public:
    Test (int &x) { t = x; }
    int getT() { return t; }
};

int main()
{
    int x = 20;
    Test t1(x);
    cout << t1.getT() << " ";
    x = 30;
    cout << t1.getT() << endl;
    return 0;
}

使用gcc编译器时显示以下错误

It is showing the following error while using gcc compiler

    est.cpp: In constructor ‘Test::Test(int&)’:
    est.cpp:8:5: error: uninitialized reference member ‘Test::t’ [-fpermissive]

为什么编译器不直接调用构造函数?

Why doesn't the compiler directly call the Constructor?

推荐答案

这是因为只能在初始化列表中初始化引用.使用

That is because references can only be initialized in the initializer list. Use

Test (int &x) : t(x) {}

说明:引用只能设置一次,发生此情况的地方是初始化列表.完成之后,您将无法设置引用,而只能将值分配给引用的实例.您的代码意味着,您尝试向引用的实例分配某些内容,但是该引用从未初始化,因此它没有引用任何int实例,您会收到错误.

To explain: The reference can only be set once, the place where this happens is the initializer list. After that is done, you can not set the reference, but only assign values to the referenced instance. Your code means, you tried to assign something to a referenced instance but the reference was never initialized, hence it's not referencing any instance of int and you get the error.

这篇关于如何初始化一个类的引用成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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