Define reference members in C++ classes

Foreword:

Let's answer a question first: Can reference data members be defined in a C++ class?

The answer is yes, but the reference in the class must be initialized through the constructor initialization list! ! !


Reference member variables can be defined in C++ classes, but the following three rules must be followed:

  1. You cannot use the default constructor to initialize, you must provide a constructor to initialize the reference member variable. Otherwise it will cause an uninitialized reference error.
  2. The formal parameters of the constructor must also be reference types
  3. You can't assign values ​​to the function body of the constructor ( why don't you say initialization ? Because all member variables are completed in the initialization list), you must initialize in the initialization list.

The constructor is divided into two stages: initialization and calculation. The former corresponds to the member initialization linked list, and the latter corresponds to the constructor function body. The reference must be completed in the initialization phase, that is, in the member initialization linked list, otherwise an error will be reported during compilation (the reference is not initialized).

Code display:

#include <iostream>
using namespace std;

class node
{
    
    
public:
	node(int &target) :st(target)
	{
    
    
		cout << "lalala" << endl;
	}
	void printst()
	{
    
    
		cout << st << endl;
	}
private:
	int &st;
};
int main()
{
    
    
	int op = 123;
	node bk(op);
	bk.printst();
	return 0;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/114323539