【问题标题】:No matching function for template class operator in C++ with .hpp and .cpp.hpp 和 .cpp 中的 C++ 模板类运算符没有匹配函数
【发布时间】:2017-01-26 14:52:13
【问题描述】:

我有两个要编译的文件。它们如下:

数组.hpp

template<class T> class Array 
{
    public:
        Array() {};
        ~Array() {};

        int width_, height_;
        std::vector<T> data_;

        template<typename U>
        void print(const Array<U>& inputArray);

        T* operator()(int x, int y);
}

数组.cpp

template<typename T> template<typename U>
void Array<T>::print(const Array<U>& inputArray)
{
    std::cout << ( *inputArray(0, 0) ) << std::endl; 
// ERROR: No matching function for call to object of type 'const Array<unsigned char>'
} 
template void Array<uint8_t>::print(const Array<uint8_t>& inputArray);
template void Array<uint8_t>::print(const Array<float>& inputArray);


template <typename T>
T* Array<T>::operator()(int x, int y)
{
    return &data_[0] + x + y*width_;
}
template uint8_t* Array<uint8_t>::operator()(int x, int y);
template float* Array<float>::operator()(int x, int y);

我完全不清楚为什么对操作员的调用会引发错误。为函数“print”实例化的两种输入类型都明确定义了运算符。 是不是因为编译器先在头文件中查找,找不到指定类型的操作符实例。 在头文件中定义运算符也没有多大用处。这(据我所知)再次引发错误,因为在头文件中实现了两个函数(运算符),名称相同但返回类型不同。

怎么办?

【问题讨论】:

标签: c++ templates linker-errors template-classes


【解决方案1】:

你的功能

void Array<T>::print(const Array<U>& inputArray)

接受 const 引用,而它正在调用的方法:

T* operator()(int x, int y);

不是 const 因此错误。

【讨论】:

    【解决方案2】:

    第一个问题是void print(const Array&lt;U&gt;&amp; inputArray); 不是constvoid Array&lt;T&gt;::print(const Array&lt;U&gt;&amp; inputArray) const 是。这些不是相同的功能。也许您打算将print 设为静态,因为它不使用this

    第二个问题是运算符T* operator()(int x, int y);不是const而是const Array&lt;U&gt;&amp; inputArrayinputArray 只能调用 const 方法。

    您的代码还有许多其他问题,但其中任何一个都可能导致您的错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 2015-03-17
      • 2012-01-25
      相关资源
      最近更新 更多