C 中的继承和名称空间

Inheritance and Namespaces in c++

本文关键字:空间 继承      更新时间:2023-10-16

image.h

#include <iostream>
#include "Array.h"
using namespace math;
namespace imaging
{
    class Image: public Array
    {
        public:
            Image();
    };
}

array.h

namespace math
{
    template <typename T>
    class Array
    {
        protected:
            T * buffer;
            unsigned int width, height;
        public:
            Array(unsigned int w, unsigned int h);
    };
}

和array.cpp

#include <iostream>
using namespace std;
namespace math
{
    Array::Array(unsigned int w, unsigned int h)
    {
        this->width = w;
        this->height = h;
    }
}

我有这些错误:image.h:12:2:错误: { token

之前的预期类名称
{

^在image.cpp中包含的文件中:1:0:image.h:12:2:错误: { token之前的预期类名称

{

^array.cpp:8:2:错误:无效使用模板名称math::Array没有参数列表 Array::Array(unsigned int w, unsigned int h)

为此有任何帮助吗???thnx

您需要将Array构造函数的定义放在标题中,并使用模板的正确语法:

namespace math
{
    template<typename T>
    Array::Array(unsigned int w, unsigned int h)
    {
        this->width = w;
        this->height = h;
    }
}

一个重要的经验法则是,您不能在源文件中的template类中定义函数。(您可以在某些情况下,但确实将其视为例外而不是规则。)

没有<>Array被假定为在这里并非如此的非模板类,从而导致错误。

您在这里有问题:

namespace imaging
{
    class Image: public Array

应该是

namespace imaging
{
   template <typename T>
   class Image: public Array<T>