简体   繁体   English

我的复制构造函数导致使用我的类的方法失败。 有人可以看一下,然后告诉我我做错了什么吗?

[英]My copy constructor is causing my methods which use my class to fail. Can someone take a look at it and tell me what I am doing incorrectly?

My constructor creates a copy just fine - but when a method takes an IntegerNumber as an argument, it stops working. 我的构造函数很好地创建了一个副本-但是当一个方法将IntegerNumber作为参数时,它将停止工作。

My constructor: 我的构造函数:

IntegerNumber::IntegerNumber(const IntegerNumber &integerInput){
//Creates a copy of an Integer Number
//Set len and isNegative
len = integerInput.len; 
isNegative = integerInput.isNegative;
//Fill integer with IntegerInput
integer = new char[len+1];
for(int i = 0; i <= len; i++)
    integer[i]=integerInput.integer[i];
}

My destructor: 我的析构函数:

IntegerNumber::~IntegerNumber(){
//Destructs IntegerNumber
delete [] integer;
delete &len;
delete &isNegative;
}

My Class' data members: 我班的数据成员:

private:
    char *integer;
    int len;
    bool isNegative;

Please try and help me figure out what could be wrong with my constructor/destructor such that the program stops but doesnt crash or break? 请尝试帮助我弄清楚我的构造函数/析构函数可能出了什么问题,从而使程序停止但不会崩溃或中断?

you dont want this: 你不想要这样:

delete &len;
delete &isNegative;

deleting instance variables like this is undefined bahaviour so your program can stop 删除这样的实例变量是未定义的行为,因此您的程序可以停止

Use std::unique_ptr and other classes to manage memory- always. 使用std::unique_ptr和其他始终管理内存。 Dynamic arrays particularly are suited to std::vector<T> . 动态数组特别适合于std::vector<T> Do not manually manage your memory- you will get ALL THE ERRORS. 不要手动管理您的内存,您将得到所有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人可以告诉我我的代码有什么问题吗? - Can someone please tell me what is wrong with my code? 有人可以告诉我为什么输入“ y”继续后仍停留在验证循环中吗? - Can someone tell me why I am stuck in my validation loop after entering 'y' to continue? 有人可以告诉我为什么我的分数总是计算为零? - Can someone tell me why my fraction always calculates as zero? 有人可以告诉我代码有什么问题吗? - Can someone tell what's wrong with my code? 我在几个测试用例中遇到错误......你能告诉我我的方法的问题吗 - I am getting error in few test cases....Can you tell me the problem with my approach 我的复制构造函数有什么问题? - What is wrong with my Copy Constructor? “预期&#39;;&#39;在return语句之后,有人能告诉我我的代码有什么问题吗? - "expected ' ; ' after return statement, could someone tell me what is wrong with my code? 复制构造函数 - 我是否正确设置了 std::strings - copy constructor - am I setting my std::strings correctly 有人可以告诉我为什么传递参数后我的字符串为空吗? - Can someone tell me why my string is blank after passing the argument? 是什么导致我的错误? 我正在尝试创建一个玩家类并将玩家名称存储为变量 - What is causing my error? I am trying to create a player class and store a players name as a variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM