C++编译器默默为你做了些什么?

    技术2025-04-03  28

    C++编译器默默为你做了些什么?

    当你很欢乐地用着C++写着一个个类的时候,你有没有想过C++编译器在暗中做了哪些手脚,这个时候你也许会一头雾水,但实际上C++编译器在幕后给你做了很多工作,如何你想更深入的理解并高效的使用C++,你必须了解C++编译器到底在背后做了什么,下面让我们看看C++编译器到底默默做了些什么?

    当你只定义了一个类的框架的时候,C++编译器默默地为你做了很多的幕后工作,它为你做了如下工作:

    1、为你定义了默认构造函数

    2、为你定义了析构函数

    3、为你定义了拷贝构造函数(浅拷贝 即逐域赋值)。

    4、为你定义了赋值运算符。

    5、为你定义了取址运算符。

    Demo代码如下:

    /* FileName: main.cpp Author: ACb0y Create Time: 2011年2月11日14:05:37 Last Modify Time: 2011年2月11日15:13:27 */ #include <iostream> using namespace std; //我们只定义了一个类的框架 //其他的什么都没有做 class NothingClass { //nothing }; class DefineClass { private: int data; public: /* 构造函数 */ DefineClass() { cout << "构造函数被调用" << endl; } /* 析构函数 */ ~DefineClass() { cout << "析构函数被调用" << endl; } /* 拷贝构造函数(浅拷贝) */ DefineClass(const DefineClass & r) { cout << "拷贝构造函数被调用" << endl; *this = r; } /* 赋值运算符,我们在这里做的是逐域赋值。 */ DefineClass & operator = (const DefineClass & r) { cout << "赋值运算符被调用" << endl; this->data = r.data; return *this; } /* 取址运输符 */ unsigned int operator & () { cout << "取址运算符被调用" << endl; char strAddress[15]; unsigned int address = (unsigned int)this; unsigned int addressTemp = address; int c = 0; //10进制的地址装化为16进制地址表示并存储在strAddress中 while (addressTemp) { int temp = addressTemp % 16; if (temp <= 9) { strAddress[c] = temp + '0'; } else { strAddress[c] = temp - 10 + 'a'; } addressTemp /= 16; ++c; } strAddress[c++] = 'x'; strAddress[c++] = '0'; for (int i = c - 1; i >= 0; --i) { printf("%c", strAddress[i]); } printf("/n"); //输出原始地址 cout << this << endl; //返回地址(10进制) return address; } }; int main() { NothingClass nothingClass1; NothingClass nothingClass2(nothingClass1); NothingClass nothingClass3; nothingClass3 = nothingClass1; cout << ¬hingClass1 << endl; cout << endl << endl; //调用了构造函数 DefineClass defineClass1; cout << endl; //调用了拷贝构造函数,赋值运算符 DefineClass defineClass2(defineClass1); cout << endl; //调用了构造函数 DefineClass defineClass3; //调用了赋值运算符 defineClass3 = defineClass1; cout << endl; //调用了取址运算符 cout << &defineClass1 << endl; return 0; }  

    运行结果如下:

     

    最新回复(0)