【发布时间】:2021-02-17 18:57:58
【问题描述】:
对于作业问题,我需要实现一个 cstring 类和重载运算符。但是,我在初始化 char 数组时遇到了麻烦。在下面的代码中,
StringClass::StringClass()
{
c = new char[10];
c = "Default";
stringlength = strlen(c);
}
#pragma once
#include <fstream>
class StringClass
{
private:
char* c;
int stringlength;
public:
StringClass();
~StringClass();
void print()const;
StringClass(char*, int);
StringClass(const StringClass*);
StringClass& operator=(const StringClass*);
friend std::istream& operator>>(std::istream&, StringClass*);
friend std::ostream& operator<<(std::ostream&, const StringClass*);
StringClass& operator+(const StringClass*);
char operator[](int);
};
对于行 c = "Default"; 我收到一个错误 const char* cannot be assigned to char*,但我没有将 c 设置为 const。如果我将 charc 更改为 const char c,我可以在构造函数中将其设置为默认值,但我无法进一步修改它。这是为什么呢?
编辑:我可以将声明更改为此并且它可以正常工作。这是正确的做法吗?
c = new char[10]{ "Default" };
完整的实现文件,
#include "StringClass.h"
#include <fstream>
#include <iostream>
StringClass::StringClass()
{
c = new char[10];
c = "Default";
stringlength = strlen(c);
}
StringClass::~StringClass()
{
c = NULL;
delete c;
}
void StringClass::print()const
{
for (int i = 0; i < 10; ++i)
std::cout << c[i];
std::cout<< std::endl;
std::cout << stringlength;
}
StringClass::StringClass(const StringClass* p)
{
for (int i = 0; i < 10; ++i)
{
c[i] = p->c[i];
}
stringlength = p->stringlength;
}
StringClass& StringClass::operator=(const StringClass* a)
{
if (this == a)
return *this;
else
{
for(int i = 0; i < 10; ++i)
c = &a->c[i];
stringlength = a->stringlength;
}
return *this;
}
//std::istream& operator>>(std::istream& in, StringClass* a)
//{
//in >> a->c >> a->stringlength;
//return in;
//}
std::ostream& operator<<(std::ostream& out, const StringClass* a)
{
out << a->c << " " << a->stringlength << std::endl;
return out;
}
StringClass& StringClass::operator+(const StringClass* a)
{
StringClass temp;
temp.c = c + *a->c;
temp.stringlength = stringlength + a->stringlength;
return temp;
}
char StringClass::operator[](int a)
{
return c[a];
}
【问题讨论】:
-
您的编辑回答了您的问题!在您的第一个代码 sn-p 中,
c = "Default";行将在前一行中分配的指针(或错误地尝试)替换为(常量)字符串文字的地址。 -
c = "Default";重新分配变量c,它不再指向你之前分配的内存。你所做的与int a = 5; a = 10;类似,然后想知道为什么a不再等于5。 -
啊,好的,谢谢!
标签: c++ pointers dynamic c-strings