创建DLL详解(2)

上一篇中我们讲到DLL导出函数的使用,这一篇我们讲下DLL导出类的使用
首先创建工程
这里写图片描述
这里写图片描述
选择DLL类型
这里写图片描述
创建工程完成后
这里写图片描述
这里DLLClass.h是我手动添加的
其实这里导出类的创建也很简单
直接再类的前面加上_declspec(dllexport)
例如class _declspec(dllexport) People
{
public:
People();
~People();
}
DLLClass.h

#ifndef _DLLCLASS_H
#define _DLLCLASS_H

#ifdef DLLEXPORT
#define AMB _declspec(dllexport)
#else
#define AMB
#endif
#include <string>
#include <iostream>
using namespace std;

class AMB People
{
public:
    People(char* name, int age);
    ~People();
    bool SetName(char* name);
    char* GetName();
    bool SetAge(int age);
    int GetAge();
    void SelfIntroduction();
private:
    char m_name[50];
    int m_age;
};

#endif

DLLClass.cpp

#include "stdafx.h"
#define DLLEXPORT
#include "DLLClass.h"

People::People(char* name, int age)
{
    strcpy_s(m_name, 50, name);
    m_age = age;
}

People::~People()
{

}

bool People::SetName(char* name)
{
    strcpy_s(m_name, 50, name);
    return true;
}

char* People::GetName()
{
    return m_name;
}

bool People::SetAge(int age)
{
    m_age = age;
    return true;
}

int People::GetAge()
{
    return m_age;
}

void People::SelfIntroduction()
{
    cout << "I am " << m_name << endl;
    cout << "I am " << m_age << " years old" << endl;
}

好了DLLClass.dll创建完成,我们用个工程来测试下
这里写图片描述
这里写图片描述
DLLTest.cpp

#include "stdafx.h"
#include "DLLClass.h"
#pragma comment(lib,"DLLClass.lib")

int _tmain(int argc, _TCHAR* argv[])
{
    People s("lihua",20);
    s.SelfIntroduction();
    cout << s.GetName() << " " << s.GetAge()<<endl;
    s.SetName("lilei");
    s.SetAge(21);
    cout << s.GetName() << " " << s.GetAge() << endl;
    s.SelfIntroduction();
    system("pause");
    return 0;
}

有一点要说明的是也可以像下面这样写

#ifdef DLLEXPORT
#define AMB _declspec(dllexport)
#else
#define AMB _declspec(dllimport)
#endif

如果不定义dllimport就无法使用静态成员变量,不过静态变量一般不常用,所以,一般也不写
运行
这里写图片描述
OK,类可以使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值