- Microsoft Visual C++ Windows Applications by Example
- Stefan Bjornander
- 173字
- 2021-07-02 12:02:24
Namespaces
Code can be placed in functions and functions can be placed in classes as methods. The next step is to create a namespace
that contains classes, functions, and global variables.
namespace TestSpace { double Square(double dValue); class BankAccount { public: BankAccount(); double GetSaldo() const; void Deposit(double dAmount); void Withdraw(double dAmount); private: double m_dSaldo; }; }; double TestSpace::Square(double dValue) { return dValue * dValue; } TestSpace::BankAccount::BankAccount() :m_dSaldo(0) { // Empty. } // ... void main() { int dSquare = TestSpace::Square(3.14); TestSpace::BankAccount account; account.Deposit(1000); account.Withdraw(500); double dSaldo = account.GetSaldo(); }
We could also choose to use the namespace
. If so, we do not have to refer to the namespace
explicitly. This is what we did with the std
namespace at the beginning of Chapter 1.
#include <iostream> using namespace std; namespace TestSpace { // ... }; // ... using namespace TestSpace; void main() { cout << square(3.14); BankAccount account; account.deposit(1000); account.withdraw(500); cout << account.getSaldo(); }
Finally, namespaces can be nested. A namespace may hold another namespace, which in turn can hold another namespace and so on.
#include <iostream> using namespace std; namespace Space1 { namespace Space2 { double Square(double dValue); }; }; double Space1::Space2::Square(double dValue) { return dValue * dValue; } void main(void) { cout << Space1::Space2::Square(3); }
推薦閱讀
- 爸媽微信e時代
- After Effects CC影視后期制作實戰從入門到精通
- IT Inventory and Resource Management with OCS Inventory NG 1.02
- 有趣的Flutter:從0到1構建跨平臺App
- 神奇的中文版Photoshop CC 2017入門書
- Oracle Fusion Middleware Patterns
- Photoshop CC 2018基礎教程(第3版)
- 攝影師的后期必修課(調色篇)
- KNIME視覺化數據分析
- MATLAB R2024a完全自學一本通
- 中文版Photoshop CS5基礎培訓教程(移動學習版)
- AI設計時代:Midjourney實戰應用手冊
- 夢幻森林Procreate童話風插畫繪制專業技法
- After Effects CS6影視后期合成案例教程(微課版)
- jQuery 1.4 Reference Guide