I'm attempting to write a simple program using an array class implemented in a header file. Whenever I compile the program, I get a "non-lvalue in assignment" error. The details are as follows:
Compiler: Bloodshed Dev-Cpp Version 4.9.9.2
Error Message: non-lvalue in assignment (location indicated in file)
Header file: arraykm.h
Main .cpp file: arraytest.cpp
Header file:
#include <iostream>
using namespace std;
Ok that removed the lvalue error.
So to clarify, the function double& element(int i) returning pt[i-1] returns a pointer to its address correct?
This may be unrelatd, but when I made the following changes to the class function prototype & implementation:
Prototype change:
double& element(int i);
Implementation change:
double& array::element(int i)
{if(i<1 || i>elements) {cout<<"array index out of bounds\n";}
return pt[i-1];}
I received a linker error stating an undefined reference to array::total. The problem is no such function exists in my array class, although a public variable total does exist. What could be causing this problem?
returning pt[i-1] returns a pointer to its address correct?
No, it returns a reference.
Similar to a pointer, but not quite the same thing.
You could accomplish the same thing with a pointer, but then the syntax would be much uglier because you'd have to dereference the pointer.
I received a linker error stating an undefined reference to array::total. The problem is no such function exists in my array class, although a public variable total does exist. What could be causing this problem?
It's kind of weird, but static members need to be instantiated in a single source file.
Put this line in your cpp file for the class:
int array::total = 0; // don't put it in any function
It's similar to how you have function prototypes and function bodies. A prototype will let you call the function, but you'll get a linker error if you don't have a function body.
Similarly, staticint total; is like the variable prototype, but not the variable body. You need to do the above code to give it a body.