gpt4 book ai didi

c++ - 静态库 : hiding private members from header file

转载 作者:搜寻专家 更新时间:2023-10-31 00:35:40 25 4
gpt4 key购买 nike

我希望将我的部分代码编译为静态库以包含在其他项目中。当然,我必须分发编译后的库和一个包含类声明和公共(public)成员的头文件,但我不知道是否可以将所有私有(private)成员和声明移动到不同于头文件的地方。

例子:

在project.h文件中:

class MyClass
{
public:
MyClass();
void Give_me_an_input(int);
int Get_your_output();

private:
int a, b;
int MySecretAlgorithm();
};

在 .cpp 文件中:

MyClass::MyClass()
{
a = 1;
b = 0;
}

void MyClass::Give_me_an_input(int c)
{
b = c;
}

int MyClass::Get_your_output()
{
return MySecretAlgorithm();
}

int MyClass::MySecretAlgorithm()
{
return (a + b);
}

有没有办法将所有私有(private)成员 int a, b;int MySecretAlgorithm(); 移动到不同于头文件的地方?

最佳答案

指针实现习语可以用在这样的场景中,通常称为pimpl .基本思想是从声明中取出实现细节并简单地有一个指向实现细节的不透明指针。

std::unique_ptr 用于以下示例;但您当然可以只使用普通指针。

// my_class declaration unit.
class my_class {
private:
class impl;
unique_ptr<impl> pimpl;

public:

};

// my_class implementation unit
class my_class::impl {
int whatever;
int whenever;
};

my_class::my_class(): pimpl( new impl )
{
}

关于c++ - 静态库 : hiding private members from header file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23416262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com