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 |