基本上据我所知,当您创建一个具有公共、受保护和私有部分以及每个公共和受保护部分中的变量/函数的基类时,将继承到子类的适当部分(由类子类定义:私有基础,它将获取基础的所有公共和受保护成员并将它们公开,将“私有”一词更改为“公开”将它们全部公开,并将其更改为“受保护”将它们全部变为“受保护”)。
因此,当您创建一个子类时,您永远不会从前一个类(在本例中为基类)的私有部分收到任何内容,如果这是真的,那么子类的对象不应该有它自己的版本基类中的私有变量或函数是否正确?
让我们来看一个例子:
#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 的第二个副本。
有人可以向我解释这一切吗,这打破了我对继承的理解。