首页 > 编程语言 >C++中关于默认构造函数(Default Constructor)

C++中关于默认构造函数(Default Constructor)

时间:2023-04-28 15:58:49浏览次数:38  
标签:初始化 bar intVal Default str Constructor Bar foo 构造函数

读<<深度探索C++对象模型>>,第二章介绍了默认构造函数,自觉知识点虽基础但是很是被忽略,故作此文记录.

关于基础概念不做介绍,先看代码

#include <stdio.h>
#include <string>

class Sample{
    
public:
    int intVal;
};

class Foo {
public:
    Foo(int a = 1000): intVal(a){

    };
    int intVal;
};

class Bar {
    
public:
    Foo foo;
    Sample sample;
    std::string str;
    int intVal;
};

void init(){
    Bar bar;
    printf("bar.foo.intVal: %d\n",bar.foo.intVal);
    printf("bar.sample.intVal: %d\n",bar.sample.intVal);
    printf("bar.str: %s\n", bar.str.c_str());
    printf("bar.intVal: %d \n",bar.intVal);
}

int main() {
    init();
    return 0;
}

代码简单明了,就是初始一个Bar对象,打印对象的 data member.再拷贝到IDE中之前,不妨猜想一下输出结果

假设已经思考了一段时间,
看下运行结果

运行环境 版本13.3.1 (22E261) Xcode Version 14.3 (14E222b) Apple Clang

foo uninit
bar.foo.intVal: 1000
bar.sample.intVal: 0
bar.str: 
bar.intVal: -1074793664 
Program ended with exit code: 0

一次试验不足以总结出什么结论,先分析看:
由输出可知:

 * Bar成员foo调用了我们自己写的构造函数,将intVal初始化为1000
 * Bar成员sample默认初始化了其member intVal为0
 * Bar成员intVal 未初始化,值为随机值(可能多次输出相同)
 * Bar成员str 初始化为空字符串

接下来将代码放到Windows平台运行

运行环境: window11 vs2019 编译器 对应vs2019的msvc++

foo uninit
bar.foo.intVal: 1000
bar.sample.intVal: -12903328372
bar.str: 
bar.intVal: -7392214732 
Program ended with exit code: 0

通过对比:
* Bar的intVal成员未初始化
Sample的intVal成员未初始化

大概总结一下:
编译器对于未初始化的字符串member 会自动初始化为空字符
不同编译器对于intVal的初始化行为是不一样的
编译器会默认调用有构造函数的对象构造方法
不要相信编译器

标签:初始化,bar,intVal,Default,str,Constructor,Bar,foo,构造函数
From: https://www.cnblogs.com/zhao-jie-li/p/17361618.html

相关文章

  • 【踩坑】.NET异步方法不标记async,Task<int> 返回值 return default问题
    ​        在.NET中,返回类型为 Task<T> 的方法并不一定要标记为 async。这是因为 async 关键字只是用来告诉编译器该方法中包含异步操作,并且可以使用 await 和其他异步特性(如 Task.WhenAll)来等待异步操作完成。如果一个方法中没有使用 await 或者其他异步特性......
  • @JvmDefault is only supported since JVM target 1.8. Recompile with '-jvm-target
    问题Logcat提示’@JvmDefault’isonlysupportedsinceJVMtarget1.8.Recompilewith'-jvm-target1.8’解决在gradle中插入以下代码android{//..其他代码...kotlinOptions{jvmTarget="1.8"}}问题Logcat提示:Usageof‘@JvmDefault......
  • 构造函数私有化或保护化
    构造函数私有化或保护化摘自:https://blog.csdn.net/caoyangxiaoyao/article/details/81184786构造函数私有化/保护化可以将构造函数设置为私有函数,但是这样做就无法从外部直接调用构造函数,因此就无法直接构造这个类的对象。1.如果你不想让外面的用户直接构造一个类(类A)的对象,而是......
  • spring 自动装配 default-autowire="byName/byType"[转]
    spring自动装配default-autowire="byName/byType"一、spring自动装配default-autowire="byName"byName,按变量名称,与id名称一样,若不一样,就报错。<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.o......
  • Vue Typescript 引入文件接口,就无法使用withDefaults
    就是代码写的不规范报错写法 import{Setting}from'@element-plus/icons-vue' import{defineProps,withDefaults}from'vue' import{PiProject}from'@/types/Project' interfaceProjectCardProps{ project:PiProject } constprops=de......
  • ESM export default {...object} All In One
    ESMexportdefault{...object}AllInOneobjectdestructuring&moduleexportdefaulterrosexport{...obj}❌constMetrics={autoReport,manualReport,};export{...Metrics,};exportdefaultMetrics;demosexportdefault{...obj}......
  • Invalid prop: type check failed for prop "defaultExpandAll". Expected Boolean, g
    vue中使用element-ui报错如下,defaultExpandAll关键词页面也搜不到[Vuewarn]:Invalidprop:typecheckfailedforprop"defaultExpandAll".ExpectedBoolean,gotStringwithvalue"true".foundin---><ElTable>atpackages/table/src/table.vue......
  • C#基础 readonly 构造函数初始化readonly字段
     .NETFramework:4.7.2       IDE:VisualStudioCommunity2019        OS:Windows10x64    typesetting:Markdown 基础代码codeusingSystem;namespaceConsoleApp{classMyClass{privatereadonlystringstr;pu......
  • context:component-scan扫描使用上的容易忽略的use-default-filters
    评:问题如下方式可以成功扫描到@Controller注解的Bean,不会扫描@Service/@Repository的Bean。正确Java代码收藏代码<context:component-scanbase-package="org.bdp.system.test.controller"><context:include-filtertype="annotation"expression="org.spri......
  • Konga versions equal to or below v0.14.9 use the default TOKEN_SECRET
    VulnerabilityDescriptionKongisaclould-native,fast,scalable,distributedmicroserviceabstractionlayer(alsoknownasAPIgateway,APImiddlewareorinsomecasesservicegrid)framework,repositoryaddress:https://github.com/Kong/kong,officialw......