代码之家  ›  专栏  ›  技术社区  ›  Yin Zhu

C++模板及其元素类型

  •  2
  • Yin Zhu  · 技术社区  · 14 年前

    这是我的模板矩阵类:

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

    但是,在我的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
    
    2 回复  |  直到 14 年前
        1
  •  7
  •   jpalecek    14 年前

    C++模板在使用它们时被实例化,而这种情况发生在 Matrix<T>::operator/(const T&) 也一样。这意味着编译器将允许 Matrix<Pixel> ,除非调用了除法运算符。

        2
  •  0
  •   SigTerm    14 年前

    1)您没有提供矩阵运算符体,因此可能不需要像素/像素运算符。

    2)afaik模板方法不会生成编译错误,除非您在代码中的某个地方调用它们。不知道这是不是标准的,但是一些版本的MSVC是这样的。做

    Matrix m;
    Pixel p;
    m = m/p
    

    在代码中的某个地方,看看会发生什么。