栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++常用概念备忘录

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++常用概念备忘录

1. 能跳过ctor直接进行dtor吗?NO!

tinyml.h

#ifndef _TINYML_H_
#define _TINYML_H_

namespace tinyml
{
    class BaseA{
    public:
        BaseA();
        ~BaseA();
    private:
        int i_;
    };
    
    auto main() -> int;
}
#endif

tinyml.cpp

#include "tinyml.h"
#include 

tinyml::BaseA::BaseA()
{
    printf("BaseA ctor called.n");
    printf("this = %pn", this);    // this = 00000002267ffb1c
    printf("&i_ = %pn", &i_);      // &i_ = 00000002267ffb1c
}

tinyml::BaseA::~BaseA()
{
    printf("&i_ = %pn", &i_);

    printf("BaseA dtor called.n");
}

auto tinyml::main() -> int
{
    tinyml::BaseA a;

    int i = 1;
    if(i < 2)
    {
        goto bug;
    }
    
    tinyml::BaseA b;

    bug:
        printf("bug exists.n");

    return 0;
}

main.cpp

#include "tinyml.h"
#include 

int main()
{
    tinyml::main();
}
图1 进入作用域时编译器就为整个作用域分配了存储空间,但是直到变量定义处才调用构造函数

图2中,企图故意跳过构造函数,如果出了作用域会调用析构函数,但变量的构造函数未被调用过(变量未初始化)因此不应该对未初始化的变量做操作,所以编译器报错。

图2 故意跳过构造函数,编译器报错 2. 其它基本概念 图3 抽象 图4 封装 图5 OOP特性 图6 这就是C++ 图7 这就是C++ 图8 this 图9 resolver 图10 Declarations vs. Definitions Default Constructor

默认构造函数是指调用时可以不提供参数的构造函数,可以是编译器提供的(auto Default Constructor)、也可以是自己写的。

图10 Declarations vs. Definitions
    struct Tree{
        int length;
        std::string name;
        //Tree(int len, std::string name):length(len), name(name){}
        //Tree(int len=3, std::string name="sometree"):length(len), name(name){} // default ctor
    };
    
    Tree trees[10] = {{3, "willow"},{5,"zhuzi"},{8,"chunshu"},{7},{}};
    for(const auto &it : trees){
        std::cout << "length: " << it.length << ", name: " << it.name << std::endl;
    }
Reference

浙大翁恺老师

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/947354.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号