用c++调用的第二个构造函数(错误的输出)

second Constructor called in c++ ( wrong output)

本文关键字:错误 输出 第二个 c++ 调用 构造函数      更新时间:2023-10-16

我正试图做一件简单的事情,但突然卡在中间。在我的代码中,我试图调用一个构造函数,在这个构造函数中我只传递长度,我的第一个构造函数初始化了一个size = length的数组,所有元素为0。

然后我将数组传递给构造函数,以给先前定义的数组其值

示例如下:

class myvector
{
  int *arr;
  int length;
public :
    myvector(int);
    myvector(int *);
};
myvector :: myvector (int len)
{
    arr =  new int [length = len];
    for ( int i=0;i< length;i++)
    {
        arr[i] = 0;
    }
}
myvector :: myvector ( int *ex)
{
    for ( int i=0;i< length;i++)
    {
        cout << ex[i] << " " << length <<" ";
        arr[i] = ex[i];
        cout << arr[i]<< " ";
    }
}
int main()
{
    myvector v1(5);
    int x[5] = {2,3,4,45,6};
    v1 = x;
}

在我的第二个构造函数中length(在第一个构造函数中定义)失去了它的值,数组arr也失去了它的值

我做什么了吗?请详细说明

我认为您不太了解调用构造函数的情况。v1 = x行不会将值放入第一次构造函数调用期间分配的内存中。相反,它构造一个new myvector(使用第二个构造函数)并将其复制到v1中。在第一个构造函数调用期间所做的事情将丢失。

听起来你想定义一个赋值操作符,而不是一个带int*参数的构造函数。此外,通常应该将单参数构造函数声明为explicit,以防止意外发生这种情况。

首先,像这样指定数组的大小时,应该提供一个常量值。在这里看到的。我强烈建议您使用std::vector<>来完成这样的任务。

但是,无论如何,就像Sneftel提到的,你似乎想要定义一个赋值操作符(更多关于在类似你的任务中重载操作符的信息,请参阅这里)。

这是我如何实现它的(不是理想的解决方案,但它有效,并给出了一个基本的想法):

#include <iostream>
using namespace std;
class myvector
{
  int *arr;
  int length;
public :
    //I completely removed second constructor 
    myvector(int);
    ~myvector();
    void operator=(const int* otherArray);
    void printArray();
};
myvector::myvector (int len)
{
    length = len;
    arr = new int[length]; // This is the way, how you can handle a non constant array sizes
    for ( int i=0;i< length;i++)
    {
        arr[i] = 0;
    }
}
void myvector::printArray()
{
    for(unsigned i = 0; i < length; ++i)
        cout<<"arr["<<i<<"] = "<<arr[i]<<endl;
}
//Here's an overloaded '=' operator.
//int x[5] = {2,3,4,45,6};
//myvector v;
//v = x; - here this function is called
void myvector::operator=(const int* otherArray)
{
    for(unsigned i = 0; i < length; ++i)
        arr[i] = otherArray[i];
}
myvector::~myvector()
{
    delete []arr; // You should ALWAYS delete what you allocated with new
}
int main()
{
    myvector v1(5);
    int x[5] = {2,3,4,45,6};
    v1 = x;
    v1.printArray();
}