初始化参考文献

0 c++ reference

我写了下面的代码,我期待得到5 6 6 6,但我得到了5 6 5 0.似乎"val"在开始时正确地获得了引用,但随后它就丢​​失了.有谁知道我的错误在哪里?

class Count {

    public:  
    void add() {  
    val++;
    }
    void print() {  
    cout << val  << endl;  
    }  
    Count(int c): val(c) {  
    }  
    private:  
    int &val;
};  

int main() {  

    int c = 5;  
    Count teste(c);  
    teste.print();  
    teste.add();  
    teste.print();  
    cout << c << endl;  
    teste.print();  
    return 0;  
}
Run Code Online (Sandbox Code Playgroud)

Bjö*_*lex 5

构造函数应该通过引用而不是值来获取参数.