重载 [] 运算符和复制构造函数不起作用
Overloading [] operator and copy constructor doesn't work
我在重载方面遇到了一个巨大的问题,[]
我完全按照示例中所示使用了它,但它不起作用,编译器甚至看不到它。
我收到错误:
与"std::cout <<* MOJ 中的"运算符<<"不匹配
第二个问题是,即使我使用复制结构,如果我删除原始对象,复制的对象也会消失。但是现在当我添加析构函数程序时,程序只是崩溃。
C:Documents and SettingsDukeMoje dokumentyMaciekKStringmain.cpp|90|error: no match for 'operator<<' in 'std::cout << * moj'|
#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <cstring>
using namespace std;
class String{
public:
char* napis;
int dlugosc;
char & operator[](int el) {return napis[el];}
const char & operator[](int el) const {return napis[el];}
String(char* napis){
this->napis = napis;
this->dlugosc = this->length();
}
String(const String& obiekt){
int wrt = obiekt.dlugosc*sizeof(char);
//cout<<"before memcpy"<<endl;
memcpy(this->napis,obiekt.napis,wrt);
//cout<<"after memcpy"<<endl;
this->dlugosc = wrt/sizeof(char);
}
~String(){
delete[] this->napis;
}
int length(){
int i = 0;
while(napis[i] != ' '){
i++;
}
return i;
}
void show(){
cout<<napis<<" dlugosc = "<<dlugosc<<endl;
}
};
int main()
{
String* moj = new String("Ala ma kota");
// cout<< moj[0] <<endl; // I GETT ERROR NO MATH FOR OPERATO<< IN STD:: COUTN<< * MOJ
String* moj2 = new String(*moj);
moj->show();
delete moj;
moj2->show();
return 0;
}
问题是moj
是一个String *
,而不是一个String
。 所以moj[0]
不会调用你的operator <<
,它只是取消引用指针。
你的问题是:
在内存分配函数未返回的任何地址上调用释放函数是一种未定义的行为。代码中存在未定义的行为,因为从不使用new []
分配内存,而是在析构函数(delete[] this->napis;
)中调用delete []
。
您没有正确实现构造函数和复制构造函数。
您需要在构造函数和复制构造函数中分配动态内存。目前,您不在构造函数中分配内存,并且在复制构造函数中执行浅拷贝而不是深拷贝。
您应该具备:
String(char* napis)
{
//I put 20 as size just for demonstration, You should use appropriate size here.
this->napis = new char[20]; <-------------- This is Important!
memcpy(this->napis,napis,12);
this->dlugosc = this->length();
}
String(const String& obiekt)
{
int wrt = obiekt.dlugosc*sizeof(char);
this->napis = new char[wrt]; <-------------- This is Important!
memcpy(this->napis,obiekt.napis,wrt);
this->dlugosc = wrt/sizeof(char);
}
此外,您需要在moj2
上调用delete
以避免在程序结束时发生内存泄漏。
delete moj2;
这是您的程序的在线版本,上面进行了上述修改,它工作得很好。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 复制构造函数、赋值运算符C++
- std::ofstream 作为类成员删除复制构造函数?
- 复制构造函数C++无法正确复制指针
- 关于复制构造函数的一个棘手问题
- 为什么调用复制构造函数而不是移动构造函数?
- 填充上编译器生成的复制构造函数之间的不一致
- C++ 对象指针数组的复制构造函数
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 防止在复制构造函数中隐式调用基构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 具有已删除移动和复制构造函数的类的就地构造
- 复制构造函数隐式转换问题
- 复制构造函数中的递归调用