部分文章内容为公开资料查询整理,原文出处可能未标注,如有侵权,请联系我,谢谢。邮箱地址:gnivor@163.com ►►►需要气球么?请点击我吧!

C++笔记-成员变量的初始值

C++内置类型的成员变量初始值的问题探讨 https://blog.csdn.net/chenqin158741019/article/details/44152663

#include <string.h>

#include <iostream>
#include <string>
#include <vector>

class Solution {
 public:
  int a;
  char c;
  std::string str;
  void print() {
    std::cout << a << "|" << c << "|" << str << "|" << str.empty() << std::endl;
  }
};

Solution x;

int main() {
  Solution s;
  Solution *s_ptr = new Solution();

  void *v_ptr = operator new(sizeof(Solution));
  Solution *s_ptr2 = new (v_ptr) Solution();

  x.print();
  s.print();
  s_ptr->print();
  s_ptr2->print();
  operator delete(s_ptr);
  operator delete(v_ptr);                                                                                                                                                                                  
  return 0;
}

发现全局变量x的内置类型初始化为0,局部变量s的内置变量没有初始化,通过动态创建的ps和ps2都初始化

变量名 默认初始化值
x 0|||1
s -1012936912|�||1
s_ptr 0|||1
s_ptr2 0|||1
posted @ 2022-01-18 10:42  流了个火  阅读(164)  评论(0编辑  收藏  举报
►►►需要气球么?请点击我吧!►►►
View My Stats