C++基礎積累(1)using namespace potter 自訂命名空間和使用

來源:互聯網
上載者:User

歡迎轉載,轉載時請註明出處:http://blog.csdn.net/aa4790139/article/details/8096741

using namespace 你會發現有n多篇文章,但基本上就是那篇文章在不停的轉載,我覺得也沒覺得多清楚,就說的大家都懂得,防止命名衝突...

自訂命名空間和自訂命名空間的使用並沒有將,今天終於理解透了....在此分享給大家....

 1、自訂命名空間定義:

第一種加入自訂類到自訂命名空間方式。

namespace potter{
 //類可以添加到這裡,但是一般都不這樣添加
 //第一種方式:這裡一般寫固定寫好了的類
 //class string;
}

第二種加入自訂類到自訂命名空間方式。

using namespace potter;
class string{//string  自訂的string

}

2、自訂命名空間的使用:

上傳我測試的demo代碼,這樣大家更容易理解...

1》命名空間類標頭檔:MyNameSpace.h(MyNameSpace.cpp什麼都沒做,不需理,建立這個MyNameSpace類,只做單純類建立命名空間用)

namespace potter{//類可以添加到這裡,但是一般都不這樣添加//第一種方式:這裡一般寫固定寫好了的類//class string;}class MyNameSpace//此下面代碼可以不管{public:MyNameSpace(void);~MyNameSpace(void);};

2》自訂string.h

#pragma once#include "MyNameSpace.h"using namespace potter;//第二種加入自訂命名空間的自訂類class string{public:string(int);~string(void);int getId();private:int id;};

3》自訂string.cpp

#include "StdAfx.h"#include "string.h"string::string(int id){this->id=id;}int string::getId(){return id;}string::~string(void){}

4》TestWin32.cpp(控制台應用程式的入口)

// TestWin32.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <string.h>//估計採用兩個string來產生衝突#include "Student1.h"#include "string.h"#include <iostream>using namespace potter;void _tmain(int argc, _TCHAR* argv[]){string s(2);std::cout<<s.getId()<<std::endl;return;};

5》運行結果:

2

 

看完這個例子後,相信你已經完全瞭解了......呵呵

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.