问题
I am trying to access derived class' private members via an object of the base class. Here is what I'm trying to do :
class A {
private:
int a, b;
public:
A(_a, _b) : a(_a), b(_b) {}
int getA() { return a; }
int getB() { return b; }
};
class B : public A {
private:
int c;
public:
B(_a, _b, _c) : A(_a, _b), c(_c) {}
int getC() { return c; }
};
vector<A*> objects;
A* retVal = new B(1,2,3);
objects.push_back(retVal);
Now how is it possible to access this?
objects[0] -> getC();
I am a little confused.
Thanks in advance.
回答1:
If you know the object is actually of derived type B
, you can do this:
static_cast<B*>(objects[0])->getC();
If you are wrong and the object is not actually of type B
(or a subclass of B
), your program will invoke undefined behavior, so don't do that.
回答2:
You can provide a pure virtual function in your base class
class A {
private:
int a, b;
public:
A(_a, _b) : a(_a), b(_b) {}
int getA() { return a; }
int getB() { return b; }
virtual int getC() = 0;
};
class B : public A {
private:
int c;
public:
B(_a, _b, _c) : A(_a, _b), c(_c) {}
virtual int getC() { return c; }
};
回答3:
I don't see any clean way to do what you want. I think it is at odds with the way inheritance is meant to be used in c++: if your derived class adds new methods then it should really be regarded as a new type, i.e. something more than just a morphing of the base type. (What you are trying to do is more objective-C-like philosophy, where methods calls are resolved runtime.) My suggestion is to reconsider your design and keep B-object conceptually separated from A-objects.
来源:https://stackoverflow.com/questions/23853357/accessing-private-members-of-a-derived-class-c