官术网_书友最值得收藏!

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);
}
主站蜘蛛池模板: 福清市| 济南市| 曲沃县| 贵州省| 阿拉善盟| 吉林省| 都兰县| 米易县| 新昌县| 馆陶县| 三亚市| 阿拉善左旗| 家居| 班玛县| 栾川县| 八宿县| 宁波市| 临高县| 长子县| 黔江区| 玛沁县| 鄄城县| 弥渡县| 甘南县| 民县| 墨玉县| 财经| 昆山市| 津市市| 射洪县| 蒲城县| 思南县| 黔西县| 波密县| 石门县| 四会市| 娄底市| 和田市| 盈江县| 沂源县| 平遥县|