これはしばらくの間私を破壊してきました。これには理由があると確信しています。
chain operator+(chain c)
{
chain<Object> result;
for (int i = 0; i < length(); i++)
{
result.insert(*(Object*)(memory+(i*sizeof(Object))));
}
for (int i = 0; i < c.length(); i++)
{
result.insert(c[i]);
}
for (int i = 0; i < result.length(); i++) // This for loop successfully shows all objects in result
{
cout << result[i];
}
return result;
}
値が返されるとき、すなわち:
chain<int> a;
cin >> a; // enter "5 6 7 8"
chain<int> b;
cin >> b; // enter "9 10 11 12"
chain <int> c = a+b;
cout << c; // Returns "0 0 7 8 9 10 11 12"
最初の2つの数字は常に0です。理由がわかりません。これは、2つのチェーンを一緒に追加する場合にのみ発生します。aまたはbを計算すると、すべての値が得られます。
誰かが共有する情報を持っているなら、私は本当に感謝します:)
編集**
フルソース
#ifndef CHAIN_H
#define CHAIN_H
#include <iostream>
#include <stdlib.h>
using namespace std;
template <class Object>
class chain
{
public:
chain(){
memorySize = 8;
memory = calloc(memorySize, sizeof(Object));
count = 0;
}
chain(Object item){
memorySize = 8;
memory = calloc(memorySize, sizeof(Object));
count = 0;
insert(item);
}
chain(chain & original){
memorySize = 8;
memory = calloc(memorySize, sizeof(Object));
count = 0;
for (int i = 0; i < original.length(); i++)
{
insert(original[i]);
}
}
~chain(){
free(memory);
}
chain operator+(chain c){
chain<Object> result;
for (int i = 0; i < length(); i++)
{
result.insert(this->operator[](i));
}
for (int i = 0; i < c.length(); i++)
{
result.insert(c[i]);
}
for (int i = 0; i < result.length(); i++)
{
cout << result[i];
}
return result;
}
Object & operator[](int pos){
return *(Object*)(memory+(pos*sizeof(Object)));
}
int length(){
return count;
}
void insert(Object item){
if (count == memorySize)
{
doubleMemory();
}
this->operator[](count) = item;
count++;
}
private:
int count;
int memorySize;
void * memory;
void doubleMemory(){
memorySize *= 2;
memory = realloc(memory, (memorySize*sizeof(Object)));
}
};
template <class Object>
ostream& operator<<(ostream& out, chain<Object>& c){
for (int i = 0; i < c.length(); i++)
{
out << c[i] << " ";
}
}
template <class Object>
istream& operator>>(istream& in, chain<Object>& c){
char ch;
int number = 0;
int sign;
while(ch != '\n')
{
ch = in.get();
if (ch == '-')
{
sign = 1;
}
else if (ch >= '0' && ch <= '9')
{
number *= 10;
number += (ch-48);
}
else if (ch == ' ' || ch == '\n')
{
number = sign == 1? 0 - number : number;
c.insert(number);
sign = 0;
number = 0;
}
}
}
#endif
これが私がテストしているコードです:
#include "chain.h"
using namespace std;
int main(){
chain<int> a, b, c;
chain<int> d(10);
chain<int> e(d);
cin >> a;
cout << endl;
cout << endl;
c = a+d;
cout << c;
}
〜