[英]Can I provide only partial class definitions as header for static library built with namespace?
我正在用C ++构建一个静态库。 它包含许多彼此交互的类。 用户将使用某些类。 这些类具有公共变量和属性。 但是,其中某些方法和属性只能由库中的其他类使用,我不希望用户将它们弄乱。 我想以某种方式将它们隐藏在传递给用户的头文件中。
构建库之后,我将最终用户应该可以访问的所有类的标题合并到一个标题中。 这样,我可以传递单个.a文件和单个.hpp文件。
但是,我不想授予对类的所有公共方法的访问权限,因为某些方法只能在库中使用,而不能由最终用户使用。
我以为我将从类定义内的统一头文件中删除我不希望用户访问的方法(它们仍保留在库的头文件中)。 这似乎有效。
然后,我以为我也将删除变量(它们仍然保留在库的头文件中)。 但这似乎失败了。
这就是我的想法:
//// Within the library
// Class1.hpp
namespace Library {
class Class1 {
public:
int Var1;
Class1(int param);
void InternalMethod();
void ExternalMethod();
private:
int Var1;
void PrivateMethod();
}
}
// Class2.hpp
namespace Library {
class Class2 {
public:
int Var1;
Class2(Class1 param);
void InternalMethod();
void ExternalMethod();
}
}
//// Header passed to user (what I would like to have)
// Library.hpp
namespace Library {
class Class1 {
public:
Class1(int param);
void ExternalMethod();
}
class Class2 {
public:
Class2(Class1 param);
void ExternalMethod();
}
}
有可能这样做吗?
谢谢!
您不能从类声明中删除变量。 如果这样做,您将声明完全不同的类。
这个怎么样。
namespace Library {
// Exposed to client
// Inerface.h
struct Interface {
~Interface() = default;
virtual void ExternalMethod() = 0;
};
// Exposed to Client
// Factory.h
std::unique_ptr<Interface> ConstructClass();
// Factory.cpp
#include "Foo.h"
std::unique_ptr<Interface> ConstructClass() {
return std::make_unique<Foo>();
}
// Class not exposed to client. This can even reside in a distinct namespace to maintain the separation.
// Foo.h
class Foo : public Interface {
public:
void ExternalMethod() override;
void InternalMethod(); //< This is no longer exposed.
};
}
我认为friend
关键字将成为您的... ...朋友:)
您可以将“内部方法”声明为私有。 然后,如果库中的其他类必须使用这些方法,则将它们声明为friend。
就这样 !
例:
.h :
// class A, accessible by user
class A
{
private:
int a;
int b;
public:
A(int aa = 0, int bb = 0);
bool externalMethod();
private:
int internalMethod(); // Method hidden for users
friend class B; // class B is friend of class A and can use its private or protected members/methods too
};
// class B, part of the library
class B
{
public:
B();
int accessInternaMethodOf(A & a);
};
.cpp :
A::A(int aa, int bb) : a(aa), b(bb)
{}
bool A::externalMethod()
{
return (a == b); // Do something
}
int A::internalMethod()
{
return (a+b); // Do something
}
B::B()
{}
int B::accessInternaMethodOf(A & a)
{
return a.internalMethod(); // access to private method through friendship
}
您可以通过以下方式运行此示例:
int main()
{
A a(5, 2);
B b;
std::cout << b.accessInternaMethodOf(a) << std::endl;
return 0;
}
结果:7
这是我对您的问题的最佳解决方案。 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.