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