晟辉智能制造

VC开发技术大全代码如何快速上手应用?

这个“大全”将以一个多功能控制台应用程序的形式呈现,它将分模块演示VC++最核心的几大技术,您可以将这些模块视为独立的教程,并组合成一个完整的项目。

VC开发技术大全代码如何快速上手应用?-图1
(图片来源网络,侵删)

VC++ 开发技术大全 - 代码框架

这个项目将包含以下模块:

  1. 基础语法Hello, World!、数据类型、流程控制。
  2. 面向对象:类、封装、继承、多态。
  3. STL (标准模板库)vector, string, map, algorithm 的使用。
  4. Windows MFC (基础框架):创建一个简单的窗口。
  5. 文件操作:读写文本文件和二进制文件。
  6. 多线程:使用 std::thread 实现多任务。
  7. 网络编程:使用 Winsock 进行简单的 TCP 通信。
  8. 数据库访问:使用 ODBC 连接 Access 数据库。
  9. 内存管理:智能指针 std::unique_ptrstd::shared_ptr
  10. 调试与异常处理:使用 try-catchOutputDebugString

第一步:创建项目

  1. 打开 Visual Studio。
  2. 选择 “创建新项目” (Create a new project)
  3. 搜索并选择 “Windows 控制台应用程序” (Windows Console Application)
  4. 给项目命名,VCPlusPlusTechniques
  5. 确保 “解决方案” (Solution)“项目” (Project) 位置正确,然后点击 “创建” (Create)

第二步:项目结构

在您的 VCPlusPlusTechniques.cpp 文件中,我们将把所有代码放在一起,为了清晰,我会用注释和函数来组织代码。

需要包含的头文件:

// 标准输入输出
#include <iostream>
// 字符串处理
#include <string>
// 向量容器
#include <vector>
// 映射容器
#include <map>
// 算法库
#include <algorithm>
// 文件流
#include <fstream>
// 内存管理
#include <memory>
// 线程库 (C++11)
#include <thread>
// 互斥锁,用于多线程同步
#include <mutex>
// 时间库,用于延时
#include <chrono>
// 异常处理
#include <stdexcept>
// ODBC 数据库头文件
#include <sql.h>
#include <sqlext.h>
// Windows Sockets 网络编程头文件
#include <winsock2.h>
#include <ws2tcpip.h>
// 为了使用 MFC,需要创建一个 MFC 项目,但这里我们先展示纯 Windows API
// #include <afxwin.h> // MFC 主头文件
// 避免在 Windows 头文件中使用 min/max 宏
#define NOMINMAX
// Windows 头文件
#include <windows.h>
// 使用标准命名空间
using namespace std;
// 全局互斥锁,用于保护 cout,防止多线程输出混乱
mutex cout_mutex;

第三步:分模块代码实现

我们将所有功能封装在 main 函数调用的子函数中。

VC开发技术大全代码如何快速上手应用?-图2
(图片来源网络,侵删)

模块 1: 基础语法

void BasicSyntaxDemo() {
    cout << "--- 1. 基础语法 ---" << endl;
    // 变量和数据类型
    int integerVar = 100;
    double doubleVar = 3.14159;
    char charVar = 'A';
    string stringVar = "Hello from C++";
    bool boolVar = true;
    cout << "整数: " << integerVar << endl;
    cout << "浮点数: " << doubleVar << endl;
    cout << "字符: " << charVar << endl;
    cout << "字符串: " << stringVar << endl;
    cout << "布尔值: " << boolVar << endl;
    // 流程控制
    cout << "\n--- 流程控制 ---" << endl;
    for (int i = 0; i < 5; ++i) {
        cout << "For 循环 i = " << i << endl;
    }
    int j = 0;
    while (j < 3) {
        cout << "While 循环 j = " << j << endl;
        j++;
    }
    if (integerVar > 50) {
        cout << "integerVar 大于 50" << endl;
    } else {
        cout << "integerVar 不大于 50" << endl;
    }
    cout << "---------------------\n" << endl;
}

模块 2: 面向对象

// 定义一个基类
class Animal {
public:
    // 虚函数,支持多态
    virtual void makeSound() const {
        cout << "动物发出声音" << endl;
    }
    // 虚析构函数,防止内存泄漏
    virtual ~Animal() {
        cout << "Animal 析构函数被调用" << endl;
    }
};
// 定义一个派生类
class Dog : public Animal {
public:
    void makeSound() const override { // 使用 override 关键字明确表示重写
        cout << "汪汪!" << endl;
    }
    ~Dog() {
        cout << "Dog 析构函数被调用" << endl;
    }
};
void ObjectOrientedDemo() {
    cout << "--- 2. 面向对象 ---" << endl;
    // 封装:将数据和方法打包在类中
    Animal* myAnimal = new Animal();
    Animal* myDog = new Dog();
    myAnimal->makeSound(); // 调用基类方法
    myDog->makeSound();    // 调用派生类方法,体现了多态
    delete myAnimal;
    delete myDog;
    cout << "---------------------\n" << endl;
}

模块 3: STL 容器和算法

void StlDemo() {
    cout << "--- 3. STL 容器和算法 ---" << endl;
    // vector: 动态数组
    vector<int> numbers = {10, 20, 30, 40, 50};
    cout << "Vector 中的元素: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    // string
    string greeting = "Hello, STL";
    cout << "字符串: " << greeting << ", 长度: " << greeting.length() << endl;
    // map: 键值对容器
    map<string, int> ages;
    ages["Alice"] = 30;
    ages["Bob"] = 25;
    ages["Charlie"] = 35;
    cout << "Bob 的年龄: " << ages["Bob"] << endl;
    // algorithm: 查找
    auto it = find(numbers.begin(), numbers.end(), 30);
    if (it != numbers.end()) {
        cout << "在 Vector 中找到了 30" << endl;
    }
    // algorithm: 排序
    sort(numbers.begin(), numbers.end(), greater<int>()); // 降序排序
    cout << "排序后的 Vector: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    cout << "---------------------\n" << endl;
}

模块 4: Windows MFC (简化版 - 纯 Windows API)

创建一个真正的窗口需要更多代码,这里我们展示核心逻辑。

// 窗口过程函数 - 处理消息
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        case WM_PAINT: {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hwnd, &ps);
            FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
            // 在这里可以绘制文本或图形
            TextOut(hdc, 50, 50, L"Hello, Windows API!", 20);
            EndPaint(hwnd, &ps);
            return 0;
        }
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
void WindowsApiDemo() {
    cout << "--- 4. Windows API (窗口创建) ---" << endl;
    cout << "注意:此功能会弹出一个窗口,请手动关闭后程序才会继续。" << endl;
    cout << "正在注册窗口类..." << endl;
    WNDCLASS wc = {0};
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = GetModuleHandle(NULL);
    wc.lpszClassName = L"MyWindowClass";
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    if (!RegisterClass(&wc)) {
        cout << "窗口类注册失败!" << endl;
        return;
    }
    cout << "窗口类注册成功,正在创建窗口..." << endl;
    HWND hwnd = CreateWindowEx(
        0, L"MyWindowClass", L"我的第一个窗口",
        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 500, 400,
        NULL, NULL, GetModuleHandle(NULL), NULL
    );
    if (hwnd == NULL) {
        cout << "窗口创建失败!" << endl;
        return;
    }
    ShowWindow(hwnd, SW_SHOW);
    UpdateWindow(hwnd);
    // 消息循环
    MSG msg = {0};
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    cout << "窗口已关闭,继续执行。" << endl;
    cout << "---------------------\n" << endl;
}

模块 5: 文件操作

void FileOperationsDemo() {
    cout << "--- 5. 文件操作 ---" << endl;
    // 写入文本文件
    string textToWrite = "这是第一行,\n这是第二行。";
    ofstream outFile("my_test_file.txt");
    if (outFile.is_open()) {
        outFile << textToWrite;
        outFile.close();
        cout << "成功写入文本文件 my_test_file.txt" << endl;
    } else {
        cout << "无法打开文件进行写入!" << endl;
    }
    // 读取文本文件
    ifstream inFile("my_test_file.txt");
    string line;
    if (inFile.is_open()) {
        cout << "\n从文件读取的内容:" << endl;
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cout << "无法打开文件进行读取!" << endl;
    }
    cout << "---------------------\n" << endl;
}

模块 6: 多线程

// 线程要执行的函数
void threadFunction(int id) {
    lock_guard<mutex> lock(cout_mutex); // 使用互斥锁保护 cout
    cout << "线程 " << id << " 开始执行。" << endl;
    // 模拟耗时操作
    this_thread::sleep_for(chrono::seconds(1));
    cout << "线程 " << id << " 执行完毕。" << endl;
}
void MultiThreadingDemo() {
    cout << "--- 6. 多线程 ---" << endl;
    thread t1(threadFunction, 1);
    thread t2(threadFunction, 2);
    cout << "主线程继续执行..." << endl;
    // 等待线程完成
    t1.join();
    t2.join();
    cout << "所有线程已执行完毕。" << endl;
    cout << "---------------------\n" << endl;
}

模块 7: 网络编程 (TCP Client)

void NetworkingDemo() {
    cout << "--- 7. 网络编程 (TCP Client) ---" << endl;
    cout << "此功能需要一个正在运行的 TCP 服务器 (在端口 8888 上)。" << endl;
    cout << "如果没有服务器,此部分可能会超时失败。" << endl;
    // 初始化 Winsock
    WSADATA wsaData;
    int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (result != 0) {
        cout << "WSAStartup 失败: " << result << endl;
        return;
    }
    // 创建套接字
    SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        cout << "创建套接字失败: " << WSAGetLastError() << endl;
        WSACleanup();
        return;
    }
    // 设置服务器地址
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(8888);
    inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr); // 连接到本地
    // 连接服务器
    result = connect(ConnectSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));
    if (result == SOCKET_ERROR) {
        cout << "连接服务器失败: " << WSAGetLastError() << endl;
        closesocket(ConnectSocket);
        WSACleanup();
        return;
    }
    cout << "成功连接到服务器!" << endl;
    // 发送数据
    string sendMsg = "Hello from VC++ Client!";
    result = send(ConnectSocket, sendMsg.c_str(), sendMsg.length(), 0);
    if (result == SOCKET_ERROR) {
        cout << "发送数据失败: " << WSAGetLastError() << endl;
    } else {
        cout << "已发送: " << sendMsg << endl;
    }
    // 关闭套接字和清理 Winsock
    closesocket(ConnectSocket);
    WSACleanup();
    cout << "---------------------\n" << endl;
}

模块 8: 数据库访问 (ODBC)

准备工作:

  1. 创建一个 Access 数据库 test.mdb
  2. 在其中创建一个表 Users,包含 ID (自动编号, 主键) 和 Name (文本) 字段。
  3. 在 "控制面板" -> "管理工具" -> "数据源 (ODBC)" 中创建一个系统 DSN,指向你的 test.mdb,数据源名称设为 MyTestDB
void DatabaseDemo() {
    cout << "--- 8. 数据库访问 (ODBC) ---" << endl;
    cout << "请确保已创建 Access 数据库 'test.mdb' 和 'Users' 表,并配置了名为 'MyTestDB' 的系统 DSN。" << endl;
    SQLHENV henv; // 环境句柄
    SQLHDBC hdbc; // 连接句柄
    SQLHSTMT hstmt; // 语句句柄
    // 分配环境句柄
    if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv) != SQL_SUCCESS) {
        cout << "分配环境句柄失败!" << endl;
        return;
    }
    // 设置 ODBC 版本
    if (SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0) != SQL_SUCCESS) {
        cout << "设置 ODBC 版本失败!" << endl;
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return;
    }
    // 分配连接句柄
    if (SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc) != SQL_SUCCESS) {
        cout << "分配连接句柄失败!" << endl;
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return;
    }
    // 连接到数据源
    SQLCHAR connStrOut[1024];
    SQLSMALLINT connStrOutLen;
    if (SQLDriverConnect(hdbc, NULL, (SQLCHAR*)"DSN=MyTestDB;", SQL_NTS, connStrOut, 1024, &connStrOutLen, SQL_DRIVER_COMPLETE) != SQL_SUCCESS) {
        cout << "连接数据库失败! 请检查 DSN 是否正确。" << endl;
        SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return;
    }
    cout << "成功连接到数据库!" << endl;
    // 分配语句句柄
    if (SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt) != SQL_SUCCESS) {
        cout << "分配语句句柄失败!" << endl;
        SQLDisconnect(hdbc);
        SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return;
    }
    // 执行查询
    if (SQLExecDirect(hstmt, (SQLCHAR*)"SELECT * FROM Users;", SQL_NTS) != SQL_SUCCESS) {
        cout << "执行查询失败!" << endl;
        SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
        SQLDisconnect(hdbc);
        SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return;
    }
    // 绑定列并获取结果
    SQLINTEGER id;
    SQLCHAR name[50];
    SQLLEN idLen, nameLen;
    SQLBindCol(hstmt, 1, SQL_C_ULONG, &id, 0, &idLen);
    SQLBindCol(hstmt, 2, SQL_C_CHAR, name, sizeof(name), &nameLen);
    cout << "\n查询结果:" << endl;
    while (SQLFetch(hstmt) == SQL_SUCCESS) {
        cout << "ID: " << id << ", Name: " << name << endl;
    }
    // 释放资源
    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
    SQLDisconnect(hdbc);
    SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
    SQLFreeHandle(SQL_HANDLE_ENV, henv);
    cout << "---------------------\n" << endl;
}

模块 9: 内存管理 (智能指针)

class Resource {
public:
    Resource() { cout << "Resource 被创建。" << endl; }
    ~Resource() { cout << "Resource 被销毁。" << endl; }
    void doSomething() { cout << "Resource 正在工作。" << endl; }
};
void MemoryManagementDemo() {
    cout << "--- 9. 内存管理 (智能指针) ---" << endl;
    // unique_ptr: 独占所有权,不能复制
    cout << "使用 unique_ptr:" << endl;
    {
        unique_ptr<Resource> res1 = make_unique<Resource>();
        res1->doSomething();
        // unique_ptr<Resource> res2 = res1; // 编译错误!
    } // res1 超出作用域,自动 delete,无需手动管理
    cout << "unique_ptr 示例结束,\n" << endl;
    // shared_ptr: 共享所有权,引用计数
    cout << "使用 shared_ptr:" << endl;
    {
        shared_ptr<Resource> res1 = make_shared<Resource>();
        {
            shared_ptr<Resource> res2 = res1; // 引用计数 +1
            cout << "引用计数: " << res1.use_count() << endl; // 输出 2
            res2->doSomething();
        } // res2 超出作用域,引用计数 -1
        cout << "引用计数: " << res1.use_count() << endl; // 输出 1
        res1->doSomething();
    } // res1 超出作用域,引用计数为0,自动 delete
    cout << "shared_ptr 示例结束。" << endl;
    cout << "---------------------\n" << endl;
}

模块 10: 调试与异常处理

void DebuggingAndExceptionDemo() {
    cout << "--- 10. 调试与异常处理 ---" << endl;
    // OutputDebugString: 输出到调试器输出窗口
    OutputDebugStringA("这是一条输出到调试器的信息,\n");
    try {
        cout << "尝试执行可能出错的代码..." << endl;
        // 模拟一个错误
        if (true) { // 改成 false 来测试正常流程
            throw runtime_error("这是一个手动抛出的异常!");
        }
        cout << "这部分代码不会执行,如果异常被抛出。" << endl;
    } catch (const exception& e) {
        // 捕获异常
        cerr << "捕获到异常: " << e.what() << endl;
        cerr << "异常已被处理,程序可以继续运行。" << endl;
    }
    cout << "---------------------\n" << endl;
}

第四步:主函数 main

将所有模块组合起来。

int main() {
    cout << "VC++ 开发技术大全示例程序开始运行..." << endl << endl;
    BasicSyntaxDemo();
    ObjectOrientedDemo();
    StlDemo();
    // WindowsApiDemo(); // 注释掉,因为它会阻塞程序,需要时取消注释
    FileOperationsDemo();
    MultiThreadingDemo();
    NetworkingDemo();
    DatabaseDemo();
    MemoryManagementDemo();
    DebuggingAndExceptionDemo();
    cout << "\n所有技术演示完毕,按任意键退出。" << endl;
    cin.get(); // 等待用户按键
    return 0;
}

如何编译和运行

  1. 链接库:对于网络和数据库模块,您需要链接一些库。
    • 网络: 在 项目属性 -> 链接器 -> 输入 -> 附加依赖项 中添加 Ws2_32.lib
    • 数据库: ODBC 通常由系统自动处理,但有时可能需要 odbc32.lib
  2. 字符集: 在 项目属性 -> 高级 -> 字符集 中,确保设置为 “使用 Unicode 字符集”“使用多字节字符集”,并根据代码中的宏(如 L"MyWindowClass")进行相应调整,上面的代码使用了 Unicode。
  3. 运行: 按 F5 或点击“开始调试”按钮运行程序。

这个项目为您提供了一个 VC++ 核心技术的“一站式”学习路径,每个模块都是独立的,您可以深入研究任何一个,对于更高级的主题,如 DirectX (游戏开发)COM/DCOM (组件对象模型)ATL (活动模板库)MFC (微软基础类库)UI 自动化 等,它们都建立在这个坚实的基础之上,您可以从这个框架出发,逐步探索和扩展。

VC开发技术大全代码如何快速上手应用?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇