search

Home  >  Q&A  >  body text

c++在派生类中使用基类函数的错误

#include <iostream>

class ZZ
{
public:
    void print()
    {
        std::cout << "hello\n";
    }
};

class YY : public ZZ
{
public:
    void print()
    {
        using ZZ::print;
        print();
    }
};

int main()
{
    YY temp;
    temp.print();
    getchar();
    return 0;
}

为什么上面的这段代码回报错?
error: 'ZZ' is not a namespace or unscoped enum using ZZ::print;

高洛峰高洛峰2772 days ago402

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 14:59:58

    Because your usage is wrong, this usage is c++11newly added

    class YY : public ZZ
    {
    public:
        using ZZ::print;
    };

    If you write it in a member function, it will extend the scope of a member function, which of course will not succeed. .

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:59:58

    First of all, the temp in main does not initialize the instance. . Then your subclass YY overloads the method of the parent class. Don’t write USING, just ZZ::print();

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:59:58

    To use the public function of the base class in a derived class, either you do not override it directly, or you can use ZZ::print() call in the print function in the derived class.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:59:58

    Using is written in the wrong place! It should not be written inside a member function! In addition, if the two print functions have the same name, infinite recursion will occur. The print in YY should be renamed!

    class YY : public ZZ
    {
    public:

    using ZZ::print;
    void YYprint()
    {
        print();
    }

    };

    reply
    0
  • Cancelreply