问题描述
此问题已被询问 - 超过两次,实际上,但我自己没能从派生的问题解决方案。
This question has already been asked here -- more than twice, actually --, but I myself haven't been able to derive a solution to my problem from the posts.
我有一个图书馆,与其中,一个名为 A
的类。从 A
类,我需要访问 std :: map<>
,但它是私有的。此外,基于我在文章中提到的可能性, A
类有无模板函数。
What I have is a library, with, among others, a class named A
in it. From class A
I need to access an std::map<>
, but it is private. Also, and based on the possibilities I found in the post I mentioned, class A
has no templated function.
我实际上能够重新编译库,所以我可以简单地改变可见性。 但,这将是一个很多的工作 - 我不知道更改的可见性是否不会得到任何其他的崩溃。
I'm actually able to recompile the library, so that I could simply change the visibility. However, that would be a lot of work -- and I'm not sure if changing the visibility won't get anything else to crash.
我想要做的是在 B
中:
// NOT MY CODE -- library <a.h>
class A {
private:
std::map<int, int> A_map;
};
// MY CODE -- module "b.h"
# include <a.h>
class B : private A {
public:
B() {
for (auto it(A_map.begin()); it != A_map.end(); ++it) {
...;
}
}
};
如何在不更改原始类的情况下基类要重载/专用?
How may I do it without changing the original class -- and without having any available templated method in the base class for to be overloaded/specialized?
推荐答案
你应该首先非常有信心,有效...可能有一个很好的理由,变量是私有的。修改它可能会破坏A的实例的状态,并且不能保证当您破解封装以读取它时,私有变量将处于逻辑或一致状态。
You should first be very confident that what you're trying to do is actually valid... there's probably a good reason that variable is private. Modifying it may break the state of an instance of A, and there's no guarantee a private variable will be in a logical or consistent state when you break encapsulation to read it.
有了这个警告,如果你可以修改/重新编译库声明你的类A的朋友可能是去的方式。 B拥有A的实例,因为它是一个朋友,它可以访问A实例的私有成员。
With that caveat, if you can modify / recompile the library declaring your class a friend of A is probably the way to go. Have B hold an instance of A by composition, and since it's a friend it can access private members of the A instance.
并且,因为我感觉特别邪恶这里是如何打破封装,甚至没有修改A.虽然它不是便携式(我在g ++在64位linux上工作),并涉及确定内存对象布局。为了简单起见,我将地图更改为向量。
And, because I'm feeling particularly evil here's a demo of how to break encapsulation without even modifying A. Although it's not portable (I'm working in g++ on 64-bit linux) and involves figuring out the in-memory object layout. I changed the map to a vector for simplicity.
#include<vector>
#include<iostream>
class A {
private:
int blah; //Just to make it a bit more realistic.
std::vector<int> A_vec;
public:
void outputVec() {
std::vector<int>::iterator it = A_vec.begin();
while(it != A_vec.end()) {
std::cout << *it << std::endl;
++it;
}
}
};
int main() {
A* a = new A();
std::vector<int>* v = (std::vector<int>*)(((char*)a)+sizeof(long));
v->push_back(27);
v->push_back(12);
a->outputVec();
return 0;
}
这篇关于从基类继承私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!