用c++调用的第二个构造函数(错误的输出)
second Constructor called in c++ ( wrong output)
我正试图做一件简单的事情,但突然卡在中间。在我的代码中,我试图调用一个构造函数,在这个构造函数中我只传递长度,我的第一个构造函数初始化了一个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();
}
相关文章:
- 显示错误输出的简单数组排序程序
- Dijkstra 中的错误输出
- 自定义runtime_error,如果我在 #what 中使用#c_str(),则错误输出始终为空
- 流字符串错误输出
- C++ 异常处理错误输出
- C ++中的错误输出,i = 65530,当我们打印i的值时,它给出-6状态65530
- SSE和iostream:浮点类型的错误输出
- C++将 popen 错误输出读取为字符串
- 部分透视/高斯消除 - 交换列而不是产生错误输出的行
- C++,向量:获得包含 0 的错误输出
- 数组函数错误输出
- CC1plus 错误:输出文件名指定两次
- 字符串错误输出
- 子斯特的错误输出
- 对大量c++错误输出完全一无所知.我认为这与预定义的函数和迭代器有关
- 简单程序的错误输出
- XCode调试器lldb中断,没有错误输出,但程序运行良好
- std::string::append(std::string)错误输出
- 查看大错误输出的顶行
- 使用结构的错误输出