gpt4 book ai didi

c++ - 由于缺少const而出现编译错误?

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:38 24 4
gpt4 key购买 nike

我正在尝试运行一段代码来定义作为英文字母集合的对象。 我不知道为什么它不编译。

I have tried to change from int to const int but it is not the case,

还添加了禁用 4996 消息,但没有帮助。

#include <iostream>

using namespace std;


class CharSet
{
int size;
char* pSet;
public:
// -----------------------------------
CharSet(int const size, char* set)
{
this->size = size;
pSet = new char[strlen(set) + 1];
strcpy(pSet, set);
}
// -----------------------------------

~CharSet()
{
delete[] pSet;
}
// -----------------------------------

CharSet operator*(const CharSet & other)
{
int maxSize = 0;
if (this->size >= other.size)
maxSize = this->size;
else
maxSize = other.size;

char * ret = new char[maxSize + 1];
char temp;
int index = 0;
for (int i = 0; i < this->size; i++)
{
temp = this->pSet[i];
for (int j = 0; j < other.size; j++)
{
if (other.pSet[j] == temp)
{
ret[index] = temp;
index++;
}
}
}
ret[index] = '\0';

return CharSet(maxSize, ret);
}

// -----------------------------------

bool operator()(char check)
{
bool flag = false;
for (int i = 0; i < this->size; i++)
{
if (pSet[i] == check)
flag = true;
}
return flag;
}

// -----------------------------------

friend ostream& operator<<(ostream& os, const CharSet& s)
{
os << s.pSet;
return os;
}

// -----------------------------------
};

int main()
{
CharSet s1(4, "DAQP"), s2(3, "AXZ");
cout << s1 * s2 << endl;
if (s1('Q') == true)
cout << "The element is member of the set" << endl;
else
cout << "The element is not member of the set" << endl;
return 0;
}

错误:

  1. E0289 构造函数“CharSet::CharSet”的实例与参数不匹配
  2. E0289 构造函数“CharSet::CharSet”的实例不匹配参数列表
  3. C4996 'strcpy': 此函数或变量可能不安全。考虑改用 strcpy_s。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。详情请参见在线帮助。
  4. C2664“CharSet::CharSet(const CharSet &)”:无法从
  5. 转换参数 2
  6. C2664“CharSet::CharSet(const CharSet &)”:无法将参数 2 从“const char [4]”转换为“char *”

最佳答案

您的构造函数中需要一个 const char*:

CharSet(int const size, const char* set)

感谢 @holy black cat "DAQP" 是一个 const char[],您没有为此提供构造函数(数组将隐式转换为指针)。


更好的方法是使用 std::string:

class CharSet
{
std::string pSet;
public:
// -----------------------------------
CharSet(std::string set) : pSet(set)
{
}
// -----------------------------------

~CharSet()
{
}
// -----------------------------------

CharSet operator*(const CharSet & other)
{
int maxSize = 0;

std::string ret;
char temp;
int index = 0;
for (int i = 0; i < pSet.size(); i++)
{
temp = pSet[i];
for (int j = 0; j < other.pSet.size(); j++)
{
if (other.pSet[j] == temp)
{
ret += temp;
index++;
}
}
}
return CharSet(ret);
}
// the rest of members ...
//
};

完整代码在 godblot

关于c++ - 由于缺少const而出现编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56995404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com