c++ - 在单独的命名空间中定义基类和派生类时出现编译错误

标签 c++

我在单独的命名空间中定义了基类和派生类(这是一项要求,因为多个类可以从单个基类派生,并且基于派生类的行为,它们将被放置在单独的命名空间中。)

Base.h

namespace global
{

    {
    class Base
    {
    public:
        Base();
        virtual ~Base();    

        virtual int someFunc(int arg1);
    }
}

Derived.h

namespace global
{
    namespace derived
    {

    class Derived: public Base()
    {
    public:
        Derived();
        ~Derived();
    }   
    }
}

Derived.cpp

namespace global
{
    namespace derived
    {
    Derived::Derived() {}
    Derived::~Derived() {}

    int Derived::someFunc(int arg1)
    {
    //some code here
    }
    }
}

当我尝试编译这段代码时,出现错误:

没有在类 global::derived::Derived 中声明“int global::derived::Derived::someFunc(int arg1)”成员函数。

那么,我需要在Derived中再次声明someFunc吗?

喜欢:

namespace global
{
    namespace derived
    {

    class Derived: public Base()
    {
    public:
        Derived();
        ~Derived();
        int someFunc(arg1 int);
    }   
    }
}

现在,如果在一个完全独立的命名空间中有一些函数接受基类引用,我如何将派生类引用传递给它?

tryFunc(Base &b);

Derived d;
tryFunc(d);

这是正确的吗?

谢谢。

最佳答案

你基本上已经弄清楚了一切,你必须在派生类的类主体中声明 someFunc

传递给 tryFunc(Base &b) 的方式也是正确的

关于c++ - 在单独的命名空间中定义基类和派生类时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14142539/

相关文章:

c++ - 如何在#ifdef 中添加 'or' 条件

c++ - 内存泄漏检测文件错误

c++ - 生产中的 STL vector 和 Boost Multi Array

c++ - 是否可以在模板中定义指向外部 -"C"函数类型的指针?

C++ 常量迭代器 C2662

c++ - 从文本文件中选取数组元素

c++ toupper - 标准函数?

c++ - Qt5 和 OpenCV 4

c++ - 从字符串中查找 C++ 第 n 次出现的子字符串

c++ - 两个 unordered_maps 的交集