为什么我不能通过继承访问此方法?

use*_*372 3 c++ oop inheritance

我有两个简单的类,并希望stuff通过传递int值来访问公共方法.为什么我不能用Bar的实例做到这一点?它不应该继承公共方法的东西.类型提示给出了int a参数,但它没有编译.

class Foo
{
public:
    int a;
    void stuff(int a){ std::cout << a << std::endl; }
};

class Bar : public Foo
{
protected:
    void stuff() { std::cout << "hello world"; }
};



void main()
{
    Bar b
    b.stuff(3);
}
Run Code Online (Sandbox Code Playgroud)

qua*_*dev 6

因为Bar::stuff隐藏Foo::stuff(只有名称在执行重载解析时很重要,所以忽略参数).

您可以 :

  • 通过using声明将其带入sope
  • 或者,明确地限定呼叫,例如b.Foo::stuff(3);.

注意:

  • main()必须归还int.

#include <iostream>

class Foo
{
public:
    int a;
    void stuff(int a){ std::cout << a << std::endl; }
};

class Bar : public Foo
{
public:
    using Foo::stuff;
protected:
    void stuff() { std::cout << "hello world"; }
};

int main()
{
    Bar b;
    b.stuff(3);
}
Run Code Online (Sandbox Code Playgroud)

要么 :

int main()
{
    Bar b;
    b.Foo::stuff(3);
}
Run Code Online (Sandbox Code Playgroud)