本案例實現一個test命名空間,此命名空間內有兩個函數,分別為getName()和getNameSpace(); 聲明命名空間及函數 namespace test{ const std::string& getName()和(); const std::string& getNameSpace(); ...
本案例實現一個test命名空間,此命名空間內有兩個函數,分別為getName()和getNameSpace();
- 聲明命名空間及函數
namespace test{
const std::string& getName()和();
const std::string& getNameSpace();
}
- 命名空間內實現單例類
實現一個單例類,構造函數要為private,自身對象為private
靜態成員函數(才可以調用靜態成員變數)
namespace test{
// 實現一個單例類,構造函數要為private,自身對象為private
class ThisNode{
private:
std::string name_;
std::string namespace_;
static ThisNode *thisNode;
ThisNode():name_("empty"),namespace_("namespace"){};
public:
// 靜態成員函數(才可以調用靜態成員變數)
/**
* 函數:實例化類
* 返回值:ThisNode&
*/
static ThisNode& instance(){
if(thisNode==nullptr){
std::cout << "沒有" <<std::endl;
thisNode = new ThisNode();
return *thisNode;
}else{
std::cout << "有" <<std::endl;
return *thisNode;
}
}
// 普通成員函數
const std::string& getName() const{
std::cout <<"get name:"<<name_<<std::endl;
return name_;
}
const std::string& getNameSpace() const{
std::cout <<"getNameSpace:" << namespace_ << std::endl;
return namespace_;
}
};
// 初始化靜態成員
ThisNode *ThisNode::thisNode = nullptr;
// 實現命名空間內的函數,實例化一個類,並調用函數
const std::string& getNameSpace(){
return ThisNode::instance().getNameSpace();
}
const std::string& getName(){
return ThisNode::instance().getName();
}
};
- 實現命名空間函數
首先調用的是類的靜態成員函數實例化唯一對象,然後調用對象中的方法;
// 實現命名空間內的函數,實例化一個類,並調用函數
const std::string& getNameSpace(){
return ThisNode::instance().getNameSpace();
}
const std::string& getName(){
return ThisNode::instance().getName();
}
- 調用
int main(){
// 使用
test::getNameSpace();
test::getName();
return 0;
}
全部代碼
#include<string>
#include<iostream>
// 聲明命名空間內的兩個函數
namespace test{
const std::string& getName()和();
const std::string& getNameSpace();
}
namespace test{
// 實現一個單例類,構造函數要為private,自身對象為private
class ThisNode{
private:
std::string name_;
std::string namespace_;
static ThisNode *thisNode;
ThisNode():name_("empty"),namespace_("namespace"){};
public:
// 靜態成員函數(才可以調用靜態成員變數)
/**
* 函數:實例化類
* 返回值:ThisNode&
*/
static ThisNode& instance(){
if(thisNode==nullptr){
std::cout << "沒有" <<std::endl;
thisNode = new ThisNode();
return *thisNode;
}else{
std::cout << "有" <<std::endl;
return *thisNode;
}
}
// 普通成員函數
const std::string& getName() const{
std::cout <<"get name:"<<name_<<std::endl;
return name_;
}
const std::string& getNameSpace() const{
std::cout <<"getNameSpace:" << namespace_ << std::endl;
return namespace_;
}
};
// 初始化靜態成員
ThisNode *ThisNode::thisNode = nullptr;
// 實現命名空間內的函數,實例化一個類,並調用函數
const std::string& getNameSpace(){
return ThisNode::instance().getNameSpace();
}
const std::string& getName(){
return ThisNode::instance().getName();
}
};
int main(){
// 使用
test::getNameSpace();
test::getName();
return 0;
}