[CPP]類定義及命名空間


  •  空間同std,空間內封裝 類 方法 數據 等內容
  • 通過不同命名空間調用可以解決同名函數沖突問題
  • 多文件間互相引用時通過#include "Human.h"導入
  • 使用#ifndef #define判斷命名空間只定義一次  防止重復調用
//human.h 定義命名空間及類

#pragma once

#ifndef __HUMAN_H__ //如果未定義該頭文件,則定義頭文件,使得整個項目只定義一次
#define __HUMAN_H__

#include <iostream>

namespace avdance //定義命名空間acdance
{

class Human
{
public:
    Human()
    {
        std::cout << "construct humnn!\n";
        age = 0;
        sex = 0;
    };
    ~Human()
    {
        std::cout << "destruct human!\n";
    }

public:
    void setAge(int a);
    int getAge();

    void setSex(int s);
    int getSex();

private:
    int age;
    int sex;
};

}//namespace 

#endif //__HUMAN_H__
 1 //human.cpp 實現類中方法
 2 #include "stdafx.h"
 3 #include <iostream>
 4 #include "human.h"
 5 
 6 namespace avdance
 7 {
 8 
 9 void Human::setAge(int a)
10 {
11     age = a;
12 }
13 
14 int Human::getAge()
15 {
16     return age;
17 }
18 
19 void Human::setSex(int s)
20 {
21     sex = s;
22 }
23 
24 int Human::getSex()
25 {
26     return sex;
27 }
28 
29 }//namespace 
 1 // cpp_learning.cpp : 定義控制台應用程序的入口點。
 2 // 主函數 引入human.h和命名空間avdance使得程序生效
 3 
 4 #include "stdafx.h"
 5 #include "human.h"
 6 
 7 int main()
 8 {
 9     avdance::Human *x = new avdance::Human;
10 
11     x->setAge(233);
12     x->setSex(0);
13     std::cout << x->getAge() << ' ' << x->getSex() << '\n';
14 
15     return 0;
16 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM