不可或缺 Windows Native (11) - C++: hello c++, C++ 与 C语言的区别小介

[源码下载]


不可或缺 Windows Native (11) - C++: hello c++, C++ 与 C语言的区别小介



作者:webabcd


介绍
不可或缺 Windows Native 之 C++

  • hello c++
  • C++ 与 C语言的区别小介



示例
1、hello c++
CppHello.h

// 保证文件只被编译一次(即使被多次引用,也只被编译一次)
/*
 * #ifndef 的方式依赖于宏名字不能冲突
 * #pragma once 保证同一个文件不会被多次编译,这里的“同一个文件”是指物理上的一个文件
 * #pragma once 依赖于编译器;而 #ifndef 则受语言天生的支持
*/
#pragma once 


// 包含指定头文件
/*
 * 举个例子:
 * <string.h> 是 c 标准库下的文件
 * <cstring> 包含了 c 标准库下的 string.h 文件,并放置在命名空间 std 下
 * <string> 是 c++ 标准库的 string 类,在命名空间 std 下
 */
#include <string>


// 引用命名空间 std (std - standard)
using namespace std;


// 自定义命名空间
namespace NativeDll
{
    class CppHello 
    {
    public:
        string Hello(string name);
    };
}

CppHello.cpp

/*
 * hello c++
 */

#include "pch.h" 
#include "CppHello.h" 

// 头文件中定义的命名空间
using namespace NativeDll;

// 实现头文件中的函数(之前要 using namespace NativeDll;)
string CppHello::Hello(string name)
{
    return "hello: " + name;
}

/*
什么是编译?

1、为了使计算机能执行高级语言源程序,需要用编译器(complier)把源程序翻译成二进制形式的目标程序(object program)
2、编译是以源程序文件为单位分别编译的,目标程序一般以.obj或.o作为后缀(object 的缩写)
3、得到多个目标文件后,需要用连接程序(linker)将一个程序的所有目标程序和系统的库文件以及系统提供的其他信息连接起来,最终形成一个可执行的二进制文件
*/


2、C++ 与 C语言的区别小介
CppDiff.h

#pragma once 

#include <string>

using namespace std;

namespace NativeDll
{
    class CppDiff
    {
    public:
        string Demo();
    };
}

CppDiff.cpp

/*
 * C++ 与 C语言的区别小介
 */

#include "pch.h" 
#include "CppDiff.h" 

using namespace NativeDll;

struct birth
{
    int year;
    int month;
    int day;
};

string CppDiff::Demo()
{
    /*
    我是多行注释
    ANSI C 只支持多行注释,而不支持单行注释
    */


    // 我是单行注释 \
        如果单行注释后面以“\”结尾则下一行也是注释 \
        多行注释“/**/”是不能嵌套的,但是多行注释内可以有单行注释


    /*
    void fun(); // C 语言的这句代表可以传递任意参数,C++ 的这句代表不可以传递任何参数
    void fun(void); // C 语言的这句代表不可以传递任何参数,所以 C 语言建议无参数时要使用 void
    */


    // C++ 可以取寄存器变量的地址,但编译器会将其变为内存变量(因为寄存器变量无地址)


    /*
    C 语言会把字符当做 int 类型
    C++ 会把字符当做 char 类型

    比如:sizeof('a')
    ANSI C99 会将其看作为 int 类型(32 位机器上一般编译器会让 int 占用 4 字节),所以会返回 4
    ISO C++ 会将其看作为 char 类型,占 1 字节,所以返回 1
    */


    // C++ 的基本数据类型中新增了 bool 类型
    bool b = true;


    // 定义结构体变量时,C 语言要求是“struct 结构体名 变量名”,而在 C++ 中 struct 可以省略掉
    struct birth myBirth1;
    birth myBirth2;


    // 由逗号运算符连接的逗号表达式,一个表达式一个表达式地依次求解,整个表达式的值是最后一个表达式的值(注意,逗号运算符级别最低,要用括号括起来)
    int x = (x = 1, x += 1, ++x); // 3
    int y = (y = 1, y += 1, y++); // 2


    // std::string 可以非常简单地完成字符串的复制,拼接之类的功能
    std::string str1 = "webabcd";
    std::string str2 = "wanglei";
    std::string str3 = str1; // 复制字符串,相当于 strcpy
    str1 = "lalala"; // 改变 str1 不会影响 str3
    std::string str4 = str1 + " " + str2 + " " + str3; // 字符串拼接很简单


    return "看代码及注释吧";
}



OK
[源码下载]

posted @ 2015-05-14 08:51  webabcd  阅读(1925)  评论(0编辑  收藏  举报