Problem with C ++ Template Designer

code:

#include<iostream> using namespace std; template<class T, int N> class point { T coordinate[N]; public: point(const point<T,N>&); const double& operator[](int i) const { return coordinate[i]; } }; template<class T, int N> point<T,N>::point(const point<T,N>&p) { for(int i=0;i<N;i++) coordinate[i]=p.coordinate[i]; }; int main() { point<int,2> P2; point<double,3> P3; cout<<P2[0]<<P3[1]; return 0; } 

output:

 prog.cpp: In function 'int main()': prog.cpp:17: error: no matching function for call to 'point<int, 2>::point()' prog.cpp:11: note: candidates are: point<T, N>::point(const point<T, N>&) [with T = int, int N = 2] prog.cpp:18: error: no matching function for call to 'point<double, 3>::point()' prog.cpp:11: note: candidates are: point<T, N>::point(const point<T, N>&) [with T = double, int N = 3] prog.cpp: In member function 'const double& point<T, N>::operator[](int) const [with T = int, int N = 2]': prog.cpp:19: instantiated from here prog.cpp:8: warning: returning reference to temporary 

Please help me deal with errors.

+4
source share
3 answers

The default constructor created by the compiler is not provided because you created your own constructor. Therefore, when you create P2 without arguments for your constructor, you need to define a default constructor to compile it.

+5
source

When you declare a variable something like

 point<int,2> P2; 

It uses the default constructor; It can be used in two scenarios:

  • You have not declared ANY constructor in your class. this way the compiler will generate a default value automatically, and you can use it.
  • You declare / define the default constructor value explicitly (let it be empty if you do nothing)

Since you are not doing anything here: just declare an empty default constructor:

 template<class T, int N> class point { //... public: point() {} // <-- default constructor }; 

This will clear your mistakes.

There is also an Important warning :

 prog.cpp:8: warning: returning reference to temporary 

This is because of your operator [] . Change the line,

 const double& operator[](int i) const 

For

 const T& operator[](int i) const // for <int, N> you should return 'int' not 'double' 
+1
source

The problem is that with these two lines

 point<int,2> P2; point<double,3> P3; 

You are trying to create two point objects using a constructor with no parameters, no parameters.

However, this constructor is not automatically created unless you specify others. Implementing a default constructor will solve your problem

0
source

All Articles