Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C - C++ Learning > assigmnet opera...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 6 Topic 4087 of 4218
Post > Topic >>

assigmnet operator when class data members are immutable

by chuck <noemail@[EMAIL PROTECTED] > Mar 29, 2008 at 07:10 PM

Hello,
  I have a class whose data members are constant.  So, default 
assignment will not happen.  I am trying to write and assignment 
operator method that will allow assignment.

I think my assignment with the swap might be the right direction but I 
am currrently stumped.
Can anyone help with this assignment operator?

Thanks,
Chuck

incase formating is messed up
http://pastebin.ca/962759

#include <cassert>  // assert
#include <iostream> // cout, endl
#include <vector>   // vector
#include <algorithm>

struct A {
	const int i;
	
	A (int i) : i (i)
    {}
	
	A operator = (A other){
		A temp = A(other);
		//std::cout << "temp = " << temp << std::endl;
		return temp;
	}
	
	/*
	A& operator = (A other){
		A temp = A(other);
		//std::cout << "temp = " << temp << std::endl;
		std::swap(*this, temp);
		return *this;
	}
	*/
	
	friend std::ostream& operator << (std::ostream& lhs, const A& rhs)
	{	lhs << rhs.i;
        return lhs;
	}
};

int main () {
	using namespace std;
	A x(2);
	A w(3);
	vector<A> y(10, x);
	vector<A> z(5,w);
	z[2]=y[4];
	
	//2 2 2 2 2 2 2 2 2 2
	for(size_t i = 0; i < 10; ++i)
	{	cout << y[i] << " ";
	}
	cout << endl;
	
	//Problem - should be
	//3 3 2 3 3
	for(size_t i = 0; i < 5; ++i)
	{	cout << z[i] << " ";
	}
	cout << endl;
}
 




 6 Posts in Topic:
assigmnet operator when class data members are immutable
chuck <noemail@[EMAIL   2008-03-29 19:10:49 
Re: assigmnet operator when class data members are immutable
Ian Collins <ian-news@  2008-03-30 13:51:10 
Re: assigmnet operator when class data members are immutable
Ulrich Eckhardt <dooms  2008-03-30 07:51:32 
Re: assigmnet operator when class data members are immutable
Francis Glassborow <fr  2008-03-30 11:38:49 
Re: assigmnet operator when class data members are immutable
Ulrich Eckhardt <dooms  2008-03-30 18:18:38 
Re: assigmnet operator when class data members are immutable
Francis Glassborow <fr  2008-03-30 11:43:06 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Fri Jul 25 12:59:47 CDT 2008.