问题
I received homework to make program without casting using constructors so this is my code, I have two classes:
class Base {
protected:
int var;
public:
Base(int var = 0);
Base(const Base&);
Base& operator=(const Base&);
virtual ~Base(){};
virtual void foo();
void foo() const;
operator int();
};
class Derived: public Base {
public:
Derived(int var): Base(var){};
Derived(const Base&);
Derived& Derived::operator=(const Base& base);
~Derived(){};
virtual void foo();
};
here two of my functions of Derived:
Derived::Derived(const Base& base){
if (this != &base){
var=base.var;
}
}
Derived& Derived::operator=(const Base& base){
if (this != &base){
var=base.var;
}
return *this;
}
but I have an error within context when I call these rows
Base base(5);
Base *pderived = new Derived(base); //this row works perfectly
Derived derived = *pderived; // I think the problem is here
thanks for any help
回答1:
You can only access protected members from another object if that object is of the same type as the object that is trying to access it. In your example the constructor and assignment operator both take in a const Base& so there is no guarantee that the actual object will be of type Derived.
回答2:
There is an error (VS2010)
error C2248: 'Base::var' : cannot access protected member declared in class 'Base'
at the line
var=base.var;
回答3:
Derived needs to delegate copying of Base members to Base::operator=, instead of trying to put its grubby little hands on the protected members of another object.
来源:https://stackoverflow.com/questions/3048809/error-in-c-within-context