Problem creating and using template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;
template<class T, int size = 100>
class Array {
  T array[size];
public:
  T& operator[](int index) {
    
    return array[index];
  }
  int length() const { return size; }
};
class Number {
  float f;
public:
  Number(float ff = 0.0f) : f(ff) {}
  Number& operator=(const Number& n) {
    f = n.f;
    return *this;
  }
  operator float() const { return f; }
  friend ostream&
    operator<<(ostream& os, const Number& x) {
      return os << x.f;
  }
};
template<class T, int size = 20>
class Holder {
  Array<T, size>* np;
public:
  Holder() : np(0) {}
  T& operator[](int i) {
    require(0 <= i && i < size);
    if(!np) np = new Array<T, size>;
    return np->operator[](i);
  }
  int length() const { return size; }
  ~Holder() { delete np; }
};


and this is the main() function
1
2
3
4
5
6
7
int main() {
  Holder<Number> h;
  for(int i = 0; i < 20; i++)
    h[i] = i;
  for(int j = 0; j < 20; j++)
    cout << h[j] << endl;
}



After compiling the program i get the error .
error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
Error executing cl.exe.


please let me know why i am getting the error and how to resolve it .
Thanks in Advance

h[i] = i;

Uses Holder::operator[], which returns, in this case a Number&.

You then attempt to assign an integer to a Number, however a Number can only be implicitly constructed from a float
(your constructor), or assigned to from another Number (your assignment operator).

You will need to either write another Number constructor that takes an int, or an assignment operator that takes
an int on the right-hand side.
Thanks for the quick replay .
but even i write the constructor in the CNumber . Same error is comming .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class CNumber  
{
private:
	float f; 
public:
	CNumber();
	CNumber(int ii) { f = (float) ii ; }
	CNumber( float ff) ;
	virtual ~CNumber();
	CNumber& operator=( CNumber& n);
	operator float() const { return f; }
	friend ostream& operator<<( ostream& os , CNumber& x)
	{
		return os<<x.f;
	}

};


Do i have to write the assigment operator in the number that take int as parameter ?
You shouldn't.

Does it compile if you change the line to

h[ i ] = CNumber( i );
Topic archived. No new replies allowed.