【问题标题】:Alias variables in class in c++C ++中类中的别名变量
【发布时间】:2022-07-14 02:36:06
【问题描述】:

我有以下代码:

#include<iostream>
using namespace std;

class Vec{
    private:
        int& var;
    public:
        Vec(int& tmp){
            var = tmp;
        }
};
int main(){
    int x = 10;
    Vec v1(x);
}

但它给出了编译错误:error: uninitialized reference member in ‘int&amp;’ [-fpermissive]

如何解决?

【问题讨论】:

    标签: c++ class pass-by-reference


    【解决方案1】:

    您应该使用初始化列表。

    #include<iostream>
    using namespace std;
    
    class Vec{
        private:
            int& var;
        public:
            Vec(int& tmp) : var(tmp) {}
    };
    int main(){
        int x = 10;
        Vec v1(x);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-09
      • 2018-10-07
      • 2012-01-26
      • 2017-11-21
      • 2011-07-22
      • 1970-01-01
      • 2014-07-25
      • 2022-06-12
      相关资源
      最近更新 更多