zoukankan      html  css  js  c++  java
  • [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!
    ";
            age = 0;
            sex = 0;
        };
        ~Human()
        {
            std::cout << "destruct human!
    ";
        }
    
    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() << '
    ';
    14 
    15     return 0;
    16 }
  • 相关阅读:
    GDI 设备环境句柄(2)
    GDI 像素(5)
    Api+Mvc增删查改
    sql语句全
    Mvc 导出
    触发器、事务
    计算时间戳的差
    SQL行转列经典例子(转载)
    Socket (套接字)通信
    MVC上传图片
  • 原文地址:https://www.cnblogs.com/zeolim/p/12334835.html
Copyright © 2011-2022 走看看