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

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);
}
主站蜘蛛池模板: 内江市| 靖安县| 乌鲁木齐市| 奉化市| 德昌县| 汤原县| 庄河市| 台东市| 大英县| 广丰县| 五峰| 油尖旺区| 宣威市| 红安县| 沙洋县| 运城市| 兴文县| 北票市| 钟山县| 宣城市| 全南县| 萨迦县| 乐昌市| 克拉玛依市| 北安市| 英德市| 泸西县| 长海县| 东至县| 福清市| 抚州市| 云梦县| 含山县| 嘉祥县| 大悟县| 平遥县| 石河子市| 扎兰屯市| 元江| 鄂温| 深水埗区|