-1

How do I call a template constructor whith objects of another class?

Example:

#include <iostream>
using namespace std;

class RGB{
    private:
    int _R;
    int _G;
    int _B;

    public:
        RGB(int a, int b, int c){
        _R=a;
        _G=b;
        _B=c;
    }
};

class Gray{
    int _G;
    public:
    Gray(int x){
        _G=x;
    }
};

template <class T1, class T2> 
class Pixel{
    public:

     Pixel(T1 i, T2 j, int a, int b){
         foo=i;
         bar=j;
         x=a;
         y=b;
     }

     void setPixel(T1 a, T2 b){
         foo=a;
         bar=b;
     }

     void getPixel();

     private:
        int x;
        int y;
        T1 foo;
        T2 bar;

};


int main(){

    Gray g(3);
    RGB rgb(4, 5, 6); 
    Pixel<Gray,RGB> pi(g, rgb, 10,27);


    return 0;
}

I can use the constructor of the class only with the default constructors of the two classes Bar1 and Bar2 but not with the two objects of the classes that I have created before(in this case bar1 and bar2).

Errors are:

main.cpp: In instantiation of 'Pixel::Pixel(T1, T2, int, int) [with T1 = Gray; T2 = RGB]':
main.cpp:62:37: required from here
main.cpp:35:37: error: no matching function for call to 'Gray::Gray()'
main.cpp:35:37: note: candidates are:
main.cpp:26:5: note: Gray::Gray(int)
main.cpp:26:5: note: candidate expects 1 argument, 0 provided
main.cpp:23:7: note: Gray::Gray(const Gray&)
main.cpp:23:7: note: candidate expects 1 argument, 0 provided
main.cpp:35:37: error: no matching function for call to 'RGB::RGB()'
main.cpp:35:37: note: candidates are:
main.cpp:16:9: note: RGB::RGB(int, int, int)
main.cpp:16:9: note: candidate expects 3 arguments, 0 provided
main.cpp:9:7: note: RGB::RGB(const RGB&)
main.cpp:9:7: note: candidate expects 1 argument, 0 provided

The errors go away if I add default values to the RGB and Gray constructors. Sorry for the mess, I'm new here...

4

1 回答 1

6

您需要了解初始化列表

Pixel(T1 i, T2 j, int a, int b) : x(a), y(b), foo(i), bar(j) {
}

foo=i;等在Pixel构造函数的主体中分配给已经存在的对象。当您的Pixel构造函数被调用时,它会尝试为其子对象调用默认构造函数GrayRGB但是,由于您提供了用户定义的构造函数,因此这两种类型都没有生成默认构造函数。解决方案是使用初始化列表来初始化类中的子对象Pixel

另外,请注意,类的子对象是按照它们在类定义中声明的顺序构造的,因此您应该始终按照它们在构造函数初始化列表中声明的顺序来初始化它们。

于 2013-09-02T21:57:54.003 回答