将常量引用传递给函数

spe*_*007 1 c++

我试图使用传递引用将常量整数传递给函数.

#include <iostream>
using namespace std;

int test(int& num);
// changes a constant variable

int main() {
  int loopSize = 7;
  const int SIZE = loopSize;
  cout<<SIZE<<endl;
  test(loopSize);
  cout<<SIZE;
  return 0;
}

int test(int& num){
  num -= 2;
}
Run Code Online (Sandbox Code Playgroud)

但是,输出永远不会更新.

Lig*_*ica 6

SIZE并且loopSize是两个不同的对象.即使在当时SIZE以其loopSize价值开始,改变一个也不会改变另一个.SIZE不是参考.

事实上,既然SIZE是一个常数,你永远无法合理地期望它无论如何都要改变!

您是否有可能撰写以下内容?

const int& SIZE = loopSize;
//       ^
Run Code Online (Sandbox Code Playgroud)