chaohuang
chaohuang

Reputation: 4115

class template with operator overloading

I'm trying to define a class template and an operator overloading:

template<class T>
class complex{
    public:
    T x,y;
    complex(T a, T b): x(a), y(b) {}
    complex<T> operator+ (const complex<T>& c){
        complex<T> s{x+c.x, y+c.y};
        return s;
    }
};

int main(){
    complex<int> c1{1,2};
    complex<int> c2{3,4};
    complex<int> c3 = c1 + c2;
    cout << "x: " << c3.x << " y: " << c3.y << endl;
}

This works fine, but if I change the definition of operator+ overloading to:

    complex<T> operator+ (const complex<T>& c){
        complex<T> s;
        s.x = x + c.x;
        s.y = y + c.y;
        return s;
    }

it reports a compilation error:

error: no matching constructor for initialization of 'complex<int>'  
       complex<T> s;  
                  ^

So why doesn't the second definition work?

Upvotes: 1

Views: 92

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

complex<T> s;

This attempts to default-construct an instance of complex<T>.

The problem with that is there is no default constructor for this instantiated template class. The only constructor you defined in your template requires two parameters, and they are completely absent here.

You can add some reasonable, default constructor (a constructor that takes no parameters) to your template:

complex(): x(0), y(0) {}

Upvotes: 2

Related Questions