这已经摧毁了我一段时间。我敢肯定这是有原因的:
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"
前两个数字总是 0。我不知道为什么。这只发生在将两条链加在一起时;如果我计算 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;
}
~