C++ 不允许我从基类调用公共(public)方法

标签 c++ inheritance

假设我有 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/

相关文章:

java - 覆盖父类(super class)的实例变量

java - 从静态方法调用 super 方法

java - 使用 EL 向下转换

php - 如何使用 php 脚本可读的 wininet 传输文件?

c++ - 我实际上是在调用 ctor 并在指向对象的指针上初始化 vtable 吗? C++

c++ - 我们如何在 linux 中使用 c 或 c++ 调用系统函数,如 pwd 或 ls -l 而无需使用 system() 或 exec() 函数?

c++ - 二进制 '[' : no operator found which takes a left hand operand of type 'const SortableVector<int>'

c++ - C++继承中的构造函数重载问题

c++ - 不明白这个返回类型?

c++ - 从另一个类创建特定于另一个类的类的优雅/有效方法