我正在尝试运行一个定义由英文字母集合组成的对象的代码。 我不知道为什么它不能编译。
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;
}
错误:
- E0289 构造函数“CharSet::CharSet”没有实例与参数匹配
- E0289 构造函数“CharSet::CharSet”没有实例与参数列表匹配
- C4996“strcpy”:此函数或变量可能不安全。考虑使用 strcpy_s 代替。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。详情请参见在线帮助。
- C2664“CharSet::CharSet(const CharSet &)”:无法将参数 2 转换为
- 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/