简体   繁体   English

什么&#39;和&#39;代表“std :: vector <byte> &stream;“

[英]What '&' stands for in “std::vector<byte>& stream;”

I know that 我知道

void foo(vector<int>& v) { ... }

is passing vector by reference, but 通过引用传递矢量,但是

std::vector<byte>& stream;

what is that stream variable definition? 什么是流变量定义? Why '&' is there? 为什么'&'在那里?

It's a reference to a std::vector<byte> . 它是对std::vector<byte>的引用。 Because it is a reference, it allows you to change the original vector , as shown in this example: 因为它是一个引用,它允许您更改原始vector ,如下例所示:

#include <iostream>
#include <vector>

class Incrementer {
public:
    Incrementer(std::vector<int>& v) : vec(v) {}
    void increment() {
        for (auto& i : vec)
            ++i;
    }
private:
    std::vector<int>& vec;
};

int main() {
    std::vector<int> numbers { 1, 2, 3, 4 };
    Incrementer inc(numbers);
    for (auto i : numbers)
        std::cout << i << ' ';
    std::cout << '\n';

    inc.increment();

    for (auto i : numbers)
        std::cout << i << ' ';
    std::cout << '\n';
}

inc will hold a reference to numbers , so calling inc.increment() changes numbers : inc将保留对numbers的引用,因此调用inc.increment()更改numbers

1 2 3 4 
2 3 4 5 

As others said, both of these two are the references. 正如其他人所说,这两个都是参考。 However, the second one is not valid as there is no referenced variable! 但是,第二个无效,因为没有引用变量! It should be written in some way like this: 它应该以某种方式写成:

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> stream1(5);
    stream1[0] = 10;
    std::vector<int>& stream2 = stream1; // stream2 and stream1 are two names for the same variable
    stream1[0] += 55;
    cout << "stream1: " << stream1[0] << endl;
    cout << "stream2: " << stream2[0];
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM