CPP: Reference is a type

In C++, reference is at least in form, a type, same as pointer, or rather it is a special kind of pointer.

When trying to cast to a value before passing the casted variable by reference, simply cast to the data type is incorrect, we must cast to (dtype&), the same way we cast pointers.

#ifndef _PASS_BY_REF_CAST_HPP
#define _PASS_BY_REF_CAST_HPP

#include 

using namespace std;

void func(uint32_t& var1, float var2) {
  cout << "var1 = " << var1 << endl;
  cout << "var2 = " << var2 << endl;
}

int initTest() {
  int32_t var1_ins = 10;
  float var2_ins = 3.14;

  func((uint32_t&) var1_ins, var2_ins);

  return 0;
}

#endif

This fact further strengths the argument that references and pointers should be written in the same form, as dtype*/dtype& var_name, not dtype */&var_name; the latter is just silly, and the sole reason for using it is to avoid error when defining multiple vars in oneline.

你可能感兴趣的:(c++)