受保护的函数调用c ++

时间:2014-09-09 18:03:11

标签: c++ inheritance

Class Base() {
protected:
    void foo();
}
Class Derived : public Base {
    void bar();
}

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

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

2 个答案:

答案 0 :(得分:5)

注释中出现的错误是链接器错误,因此您检查过:

It's hard to tell any more without more info.


Also, your code contains invalid syntax, which causes error(s):

  • class is lower case
  • No brackets after class name
  • ; after class definition

The following code works (until it gets to the linker) on g++ version 4.9.0:

class

答案 1 :(得分:4)

问题是您缺少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;
}