Plus and equal operators

This is a discussion on Plus and equal operators within the C++ Programming forums, part of the General Programming Boards category; I wrote two operators Code: template <class T> Vector<T>& operator+( const Vector<T>& vec, const T& value ) { Vector<T> tempvec(vec.length()); ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    49

    Unhappy Plus and equal operators

    I wrote two operators

    Code:
    template <class T>
    Vector<T>& operator+( const Vector<T>& vec, const T& value )
    {
    	Vector<T> tempvec(vec.length()); //create temp vector
    	for(int counter=0; counter<vec.length(); counter++)
    		tempvec.SetSpecificValue(counter, value+vec.GetSpecificValue(counter));
    	return tempvec;
    }
    
    template <class T>
    Vector<T>& Vector<T>::operator=( const T& value )
    {
    	for(int counter=0; counter<capacity; counter++)
    	{
    		array[counter] = value;
    	}
    	return *this;
    }
    I know that the equal operator is working because
    Code:
    vec4//already exists
    Vector<int> vec6(vec4.length());
    vec6.print();
    vec6 = vec4;
    vec6.print();
    Is working!

    But the following does not

    Code:
    vec6 = vec4 + 5;
    vec6.print();
    Any ideas???
    Thanks.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,941
    tempvec is a local variable, but you are returning it by reference. You should return it by value instead.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    49
    Quote Originally Posted by laserlight View Post
    tempvec is a local variable, but you are returning it by reference. You should return it by value instead.
    Still not working...Help? :-(

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,941
    How does it not work? You could provide the smallest and simplest compilable program that demonstrates the error.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    49
    Quote Originally Posted by laserlight View Post
    How does it not work? You could provide the smallest and simplest compilable program that demonstrates the error.
    OK...so far so good...still something small is wrong, but when I said it doens't work I was wrong. I did a stupid printing mistake so I couldn't see the change.

    Thank you very much! hopefully I'm done with this one :-)
    Last edited by misterowakka; 01-03-2008 at 11:20 AM.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21