Well, you have not disclosed the structure of the Loan class. I am assuming it to be the following:
1 2 3 4 5 6 7
|
class Loan
{
public:
double element1;
int element2;
int element3;
};
|
If so, you should not say that you want to add 5 to every
byte of the object. Instead you write, you want to add 5 to every
element of the object. Further the compiler will generate an error in line 24 of your posted code. The error would look like the following when using g++ compiler:
no match for ‘operator+’ in ‘*(((Loan*)(((unsigned int)i) * 16u)) + newLoan) + 5’
|
To solve this, you have to define the + operator for the Loan class. Check the following code:
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
|
class Loan
{
public:
double element1;
int element2;
int element3;
public:
Loan operator+ (int n) const;
};
Loan Loan::operator+ (int n) const
{
Loan addedLoan (*this);
addedLoan.element1 += n;
addedLoan.element2 += n;
addedLoan.element3 += n;
return addedLoan;
}
int main (void)
{
int length;
/**** Determine length ****/
Loan *newLoan = new Loan [length];
Loan *result = new Loan [length];
/**** Fill the newLoan array ****/
for (int i = 0; i < length; i++)
/**** It fills result[i] after adding 5
to all the elements of newLoan[i]. ****/
result[i] = newLoan[i] + 5;
}
|
Further some words of caution. When writing to binary files, do not write/read the object directly using write/read function. This is dangerous if the class has virtual methods. Further if the file format is given by a third party vendor, the size of each entry is predefined. Try the following example. Suppose the requirement is, each entry in the binary file is a pair of a char (1 byte) and a float (4 bytes), i.e. 5 bytes all together. You would be tempted to declare a class with two variables.
1 2 3 4 5
|
class Record
{
char c;
float f;
};
|
And write the objects of this class directly to the binary file. Just for fun, do
cout << sizeof (Record) << endl;
to see its size. Is it 5?