C ++ study notes XII class const, reference, pointer

Study Notes content from: Ditai Software College Tangzuo Lin teacher's video, I appreciate your guidance

const when read-only variables? What time is constant?

1. Only use const constant literal initialization will enter the symbol table
2. Use other variables initialized const variables are read-only constants still
3 to be volatile const modified constants do not enter the symbol table

PS: can not be directly determined during initial compilation const identifier value, are treated as read-only variables
Note: type as the variable initialization const reference is the same, is called a readonly variable initialized variable, not simultaneously generate a new Read-only variables, initializes the value of the variable, even if changed, is initialized by quoted generates a new read-only variables will not change, such as:

char c = ‘c’;
char& rc = c;
const int& trc = c;

rc = ‘a’;

printf(“c = %c\n”,c); //输出a
printf(“rc = %c\n”,rc);//输出a
printf(“trc = %c\n”,trc);//输出c,因char跟int不同类型,trc是一个独立于c的只读变量

Questions about references and pointers

1. A pointer is a variable
(1) is a memory address, does not require initialization, different addresses can be saved
(2) can access the values corresponding to memory address by the pointer
(3) const pointer can be modified to become a constant or read-only variable
2 references only a new variable name of
the variable (1) a reference to an operation (assignment, taking address, etc.) are passed to the representative
variable (2) const references to all represented readonly
(3) must be referenced when you define initialization, after not representative of other variables. Because the internal compiler, used to implement a reference pointer constant, it must be initialized in the definition

Reference issues should be noted that
the sample program:

#include <stdio.h>

int a = 1;

struct SV
{
 int& x;
 int& y;
 int& z;
};


int main()
{
  int b = 2;
  int* pc = new int(3);
  SV sv = {a,b,*pc};//成功
  int& array[] = {a,b,*pc};//Error

  return 0;
}

Error reason is that, standing on the compiler's point of view, because C ++ to be compatible with the C language, and in the C language, * the address of an array is a contiguous memory space, and A, b, PC memory addresses are not continuous , so the compiler failed.

发布了14 篇原创文章 · 获赞 0 · 访问量 96

Guess you like

Origin blog.csdn.net/u012321968/article/details/104450341