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" #includetinyml::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图1 进入作用域时编译器就为整个作用域分配了存储空间,但是直到变量定义处才调用构造函数int main() { tinyml::main(); }
图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
浙大翁恺老师



