extern使用举例

一、类创建对象

AppConfig.h

class AppConfig
{ /* ... */
public:
    int getServerAddress();
};
extern AppConfig theConfig; // 声明全局配置对象

AppConfig.cpp

#include "AppConfig.h"
#include <iostream>

int AppConfig::getServerAddress()
{
    std::cout << "ksjdfkskdf" << std::endl;
    return 0;
}
AppConfig theConfig; // 在此处唯一定义并初始化,创建对象并通过对应的头文件进行暴露

main.cpp

#include "AppConfig.h" // 包含了 extern 声明
void connect()
{
    // 使用全局唯一的配置对象
    int server = theConfig.getServerAddress();
}

int main(int argc, char const *argv[])
{
    // connect(); //可以同时打开
    int b = theConfig.getServerAddress();
    return 0;
}

 

posted @ 2026-02-03 10:20  小小仓鼠  阅读(20)  评论(0)    收藏  举报