假设我有 2 个类:foo 和 foo2,它们是这样写的:
foo.h:
#ifndef __InheritanceTest__foo__
#define __InheritanceTest__foo__
#include <stdio.h>
class foo
{
public:
foo();
int getSize();
protected:
int size;
};
#endif
foo.cpp:
#include "foo.h"
foo::foo()
{
size = 23;
}
int foo::getSize()
{
return size;
}
foo2.h:
#ifndef __InheritanceTest__foo2__
#define __InheritanceTest__foo2__
#include <stdio.h>
#include "foo.h"
class foo2: foo
{
public:
foo2();
};
#endif
foo2.cpp:
#include "foo2.h"
foo2::foo2()
{
size = size *2;
}
这是我的主要内容:
#include <iostream>
#include "foo.h"
#include "foo2.h"
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
foo2 f2;
int i = f2.getSize();
std::cout << i << "\n";
return 0;
}
我遇到了两个错误:
'getSize' is a private member of foo
和
cannot cast foo2 to its private base class foo.
最佳答案
类的继承默认是私有(private)的。这意味着继承的数据成员和成员函数在派生类中是私有(private)的,只能通过其自身或类的 friend 访问。
使用关键字public
来指定公共(public)继承:
class foo2 : public foo
{ ... }
请注意,这与 struct
不同,struct
的数据成员和成员函数具有公共(public)继承和公共(public)访问权限。
关于C++ 不允许我从基类调用公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26394899/