-1

我正在做作业(并学习 C++ 的工作原理)。我的任务是:

用字段定义一些类......(没关系)从这些对象创建一个向量和数组并迭代它!(列表,按字段平均等)。

现在它可以正确地与向量一起使用,但数组不起作用:

static Cipo* cipok;  // object array
static int cep = 0;  // endpoint index
static int ccap = 0; // array size

Cipo 的默认分配运算符:

public: Cipo& operator=(const Cipo &c)
{
    return ((Cipo&)c);
}

初始化:

cipok = (Cipo*) malloc(sizeof(Cipo*)*100); // new Cipo[num] doesn't work..
ccap = 100;

测试代码:

for (int i = 0; i < 5; i++)
{
    Cipo c(43.5, "str", 12670, false, false);
    std::cout << c.ar <<" ";
    cipok[cep] = c;
    std::cout << cipok[cep].ar << " ";
    cep++;
}

结果:

12670 0 12670 0 12670 0 12670 0 12670 0

但是如果我使用向量,对象不会“消失”,push_back()对象并通过直接索引(或迭代器)从向量中读取。为什么他们会表现出这种行为?

4

2 回答 2

1

You immediate problem is likely caused by whacky implementation of operator = that does absolutely nothing. I'd recommend step through the code in debugger to see it. operator = (and copy constructor) should properly copy values into destination object.

There are many other issues with the code - your naming convention is ... interesting, you seem to try to cast whatever you have to whatever result is required for code to compile without reasoning what should actually be done. malloc in C++ code is very rarely needed...

于 2013-06-01T01:40:51.080 回答
0

I think the general problem is, I'm programming always in java (but now in university i must prog. in C/C++, naming conventions, like in java and in hungarian the Cipő is meaning Shoe). And in Java there is no pointers, and all object always acces by reference, but looks like (as i tested ) if i create a new object array the C++ will not allocate only 100 pointer which points to the object (where the object data starts), it allocated 100*sizeof(object) and for this place i can add data trougth assing operator.

it's my teory true?

So i tried to manage Object acces like in java.

Why copy the Object if itself alredy exist? (I don't like to "clone" objects).

于 2013-07-19T23:59:40.953 回答