c ++模板及其元素类型

Yin*_*Zhu 2 c++ templates

这是我的模板矩阵类:

template<typename T>
class Matrix
{
public:
....
Matrix<T> operator / (const T &num);
}
Run Code Online (Sandbox Code Playgroud)

但是,在我的Pixel类中,我根本没有定义Pixel/Pixel运算符!

为什么在这种情况下,编译器仍然编译?

像素类

#ifndef MYRGB_H
#define MYRGB_H

#include <iostream>
using namespace std;

class Pixel
{
public:
    // Constructors
    Pixel();
    Pixel(const int r, const int g, const int b);
    Pixel(const Pixel &value);
    ~Pixel();

    // Assignment operator
    const Pixel& operator = (const Pixel &value);

    // Logical operator
    bool operator == (const Pixel &value);
    bool operator != (const Pixel &value);

    // Calculation operators
    Pixel operator + (const Pixel &value);
    Pixel operator - (const Pixel &value);
    Pixel operator * (const Pixel &value);
    Pixel operator * (const int &num);
    Pixel operator / (const int &num);

    // IO-stream operators
    friend istream &operator >> (istream& input, Pixel &value);
    friend ostream &operator << (ostream& output, const Pixel &value);

private:
    int red;
    int green;
    int blue;
};

#endif
Run Code Online (Sandbox Code Playgroud)

jpa*_*cek 7

C++模板在您使用它们时实例化,这也适用于Matrix<T>::operator/(const T&).这意味着编译器将允许Matrix<Pixel>,除非您调用除法运算符.