By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,804 Members | 1,634 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,804 IT Pros & Developers. It's quick & easy.

copy assignment for different length

P: n/a
Hi All,

How do I change the copy assignment header as shown below to allow for
different array length?

bool_vector& operator= (const bool_vector& t)

Thanks,
Hans.

template<int len>
class bool_vector {
private:
bool *v;
int i;
int sz;
public:
bool_vector() {
v=new bool[sz=len];
for (i=0; i<sz; i++) v[i]=0;
};
~bool_vector() {
delete [] v;
};
bool_vector& operator= (const bool_vector& t) {
cout << "rhs=" << sz << " lhz=" << t.sz;
if (this != &t) {
delete[] v;
v=new bool[sz]; // sz=t.sz
for (i=0;i<sz;i++) if (i<t.sz) v[i]=t.v[i]; else v[i]=0;
};
return *this;
}
};

int main()
{
bool_vector<4a,b;
bool_vector<5c;
a=b;
//c=b; // fails
}
Jul 8 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Hans posted:
Hi All,

How do I change the copy assignment header as shown below to allow for
different array length?

bool_vector& operator= (const bool_vector& t)

template<int i>
bool_vector<i&operator=(const bool_vector<i&t);
--

Frederick Gotham
Jul 8 '06 #2

P: n/a
Hans wrote:
Hi All,

How do I change the copy assignment header as shown below to allow for
different array length?
It's not a copy assignment operator because bool_vector<4>
is a DIFFERENT TYPE then bool_vector<5>. It's not clear
why you even use the size as a typed arg to the vector as
it seems nothing in your class really needs to be a template.
You don't even treat the length as constant.

I don't know what you want to do with differing sized arrays
but to allow assignemnt from one to another you'll have to
template an operator= on the additional type:

template <class Rbool_vector& operator=(const bool_vector<R>&() {
...
By the way, your class needs a copy constructor.
Jul 8 '06 #3

P: n/a

"Ron Natalie" <ro*@spamcop.netwrote in message
news:44***********************@news.newshosting.co m...
Hans wrote:
>Hi All,

How do I change the copy assignment header as shown below to allow for
different array length?
It's not a copy assignment operator because bool_vector<4>
is a DIFFERENT TYPE then bool_vector<5>. It's not clear
why you even use the size as a typed arg to the vector as
it seems nothing in your class really needs to be a template.
Because I am a beginner :-)

I understand my error, the length should be handled in the constructor and
not with a template. I changed the code and now the assignment c=b works
fine.

Thanks,
Hans
Jul 8 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.