【问题标题】:protected function call c++受保护的函数调用 C++
【发布时间】:2014-11-03 06:07:35
【问题描述】:
Class Base() {
protected:
    void foo();
}
Class Derived : public Base {
    void bar();
}

void Derived::bar(){
    foo();    //this causes an error.
}

我知道我可能遗漏了一些明显的东西,但我已经转了一个小时。如何在派生类中调用受保护的函数?

【问题讨论】:

  • 会导致什么错误?
  • 你试过 Base::foo() 吗?
  • 请注意,Derived 类中的 bar() 方法是私有的,因为这是没有访问说明符的类中方法的默认可见性。
  • 听起来您忽略了将任何包含Base::foo() 定义的 .cpp 文件添加到您的项目文件(或任何与您的构建工具等效的文件)
  • -1 不包括错误,并且不发布实际代码。您认为您的问题与 protected 的方法有关,但您错了。

标签: c++ inheritance


【解决方案1】:

出现在 cmets 中的错误是链接器错误,所以你检查过吗:

如果没有更多信息,很难说出更多信息。


此外,您的代码包含无效的语法,这会导致错误:
  • class 是小写
  • 类名后没有括号
  • ; 类定义后

以下代码在g++ version 4.9.0 上有效(直到它到达链接器):

类基础{
受保护:
    无效的富();
};

派生类:公共基础{
    无效栏();
};

无效派生::bar(){
    富();
}

【讨论】:

  • @Robomoo 通过提供伪代码来询问实际代码的问题通常是行不通的……您希望伪代码如何显示问题?您希望回答者如何区分伪问题和真正的问题?
【解决方案2】:

问题是您缺少 foo() 实现。除了其他用户评论的语法错误和公开声明。以下代码编译。

#include <iostream>

class Base {
protected:
    void foo() {std::cout << "Hi there" << std::endl;}
};

class Derived : public Base {
public:
    void bar();
};

void Derived::bar(){
    foo();    //this causes an error.
}

int main (int argc, char** argv){
    std::cout << "Hello world" << std::endl;
    Derived d;
    d.bar();

    return 0;
}

【讨论】:

    猜你喜欢
    • 2017-12-12
    • 2012-06-04
    • 2011-05-27
    • 2011-05-20
    • 1970-01-01
    • 2011-05-30
    • 2014-05-08
    • 2015-08-26
    • 2016-03-26
    相关资源
    最近更新 更多