c++ - 由于缺少const而出现编译错误?
问题描述
我正在尝试运行定义作为英文字母集合的对象的代码。我不知道为什么它不编译。
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上的完整代码
推荐阅读
- php - Symfony 4 S3Client::factory 问题:'class Aws\S3\S3Client not found'
- c++ - 如何在 C++ 中使用 Keras SavedModel
- python - 如何在 Python 中使用惩罚函数时编写“优化”问题
- java - 查找数组Java中连续数字之间的最大差距
- angular - PrimeNG 表:编辑模式无法正常工作 - 编辑字段为空
- xml - XSLT 2.0 | 修改重复x次的节点的子节点
- c - 在 rasbian os 上安装星号 1.8 时收到对 SSLv3-client-method 的未定义引用
- java - 我如何在不使用 Either 的情况下在 java 中做到这一点?
- google-cloud-platform - 谷歌云平台创建防火墙规则允许来自一个且仅特定国家的请求
- bluetooth - 蓝牙(Linux/BlueZ)配对超时还是什么?