因此,当您创建一个子类时,您永远不会从先前类(在这种情况下是基类)的私有部分收到任何内容,如果这是真的,那么子类的对象应该从未拥有来自基类的私有变量或函数,对吗?
让我们举个例子:
#include <iostream>
class myClass // Creates a class titled myClass with a public section and a private section.
{
public:
void setMyVariable();
int getMyVariable();
private:
int myVariable; // This private member variable should never be inherited.
};
class yourClass : public myClass {}; // Creates a sub-class of myClass that inherits all the public/protected members into the
// public section of yourClass. This should only inherit setMyVariable()
// and getMyVariable() since myVariable is private. This class does not over-ride any
// functions so it should be using the myClass version upon each call using a yourClass
// object. Correct?
int main()
{
myClass myObject; // Creates a myClass object called myObject.
yourClass yourObject; // Creates a yourClass object called yourObject
yourObject.setMyVariable(); // Calls setMyVariable() through yourObject. This in turn calls the myClass version of it because
// there is no function definition for a yourClass version of this function. This means that this
// can indeed access myVariable, but only the myClass version of it (there isn't a yourClass
// version because myVariable is never inherited).
std::cout << yourObject.getMyVariable() << std::endl; // Uses the yourClass version of getMyVariable() which in turn
// calls the myClass version, thus it returns the myClass myVariable
// value. yourClass never has a version of myVariable Correct?
std::cout << myObject.getMyVariable() << std::endl; // Calls the myClass version of getMyVariable() and prints myVariable.
return 0;
}
void myClass::setMyVariable()
{
myVariable = 15; // Sets myVariable in myClass to 15.
}
int myClass::getMyVariable()
{
return myVariable; // Returns myVariable from myClass.
}
现在,根据我的理解,这应该打印出: 15 15 因为它总是使用myClass函数的版本(因此使用myClass myVariable)。但是,奇怪的是,情况并非如此。运行此程序的结果打印: 15 0 这让我想知道,我们不仅继承了myVariable,还能否对其进行修改?显然,这样会创建myVariable的另一个版本,否则myClass版本就不会为0。通过这样做,我们确实正在编辑第二个副本的myVariable。 请有人向我解释这一切,这已经摧毁了我对继承的理解。
myObject.getMyVariable()
是未定义的行为。 - chrismyObject.setMyVariable
。所以这只是一个简单的编程错误,与继承无关! - Oliver Charlesworth