C++ 代码类型替换失败
c++ code type substition fail
我有这段代码,但不可能用g++或msvc编译。我正在尝试制作一个自定义类型 CharNw,我可以将其用作字符串,在现有的所有字符串例程中或将所有现有函数作为参数传递:
#include <string.h>
#include <stdio.h>
void fx(unsigned int x)
{
/*this is the reason of all this
but is ok, not is problem here */
.....
}
class CharNw
{
int wt;
char cr;
public:
CharNw() { wt = -1; cr = ' '; }
CharNw( char c) { if wt > 0 fx( (unsigned int) wt); cr = c; }
operator char () { if wt > 0 fx( (unsigned int) wt); return cr ;}
assgn( int f) { wt = f;}
};
int main(void)
{
CharNw hs[40]; //it is ok
CharNw tf[] = "This is not working, Why?n";
char dst[40];
strcpy(dst, tf); //impossible to compile
printf("dst = %s, tf = %s", dst, tf); //too
return 0;
}
能帮我吗?
逐行。
CharNw hs[40]; //it is ok
以上是容量为 40 个元素的 CharNw
个对象的数组。 这很好。
CharNw tf[] = "This is not working, Why?n";
在作业的右侧 (RHS(,您有一个类型 char const * const* and on the left you have an array of
CharNw . The
CharNw' 不是字符,所以您在这里遇到了问题。 希望作业的两面具有相同的类型。
char dst[40];
字符数组。 仅此而已,仅此而已。 它的容量为 40 个字符。 dst
数组不是字符串。 您应该更愿意将#define
用于阵列容量。
strcpy(dst, tf); //impossible to compile
strcpy
要求这两个参数都指向char
。 left 参数可以分解为指向数组第一个char
的指针。 tf
是一个CharNw
数组,它与char
数组不兼容,也不与指向char
的指针兼容。
printf("dst = %s, tf = %s", dst, tf); //too
printf
格式说明符%s
需要一个指向字符的指针,最好是 C 样式、NUL 终止的字符数组(或序列(。 tf
参数是一个CharNw
数组,它不是字符数组,也不是指向单个字符或 C 样式字符串的指针。
编辑 1:转换运算符
类中operator char ()
的方法将字符变量转换为CharNw
变量。 它不适用于指针或数组。
您将需要一些混乱的指针转换函数。
下面是一个示例:
const unsigned int ARRAY_CAPACITY = 40U;
const char text[] = "I am Sam. Sam I am."
CharNw tf[ARRAY_CAPACITY];
for (unsigned int i = 0U; i < sizeof(text); ++i)
{
tf[i] = text[i]; // OK, Converts via constructor.
}
for (unsigned int i = 0U; i < sizeof(text); ++i)
{
printf("%c", tf[i]); // The tf[i] should use the operator char () method.
}
更好的方法是使用 std::basic_string
声明一个类,而不是试图将类压缩到 C 样式字符串函数中。
例如:
class StringNw : public std::basic_string<CharNw>
{
};
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 要求子句中不允许哪些替换失败?
- 模板参数推导/替换失败,lambda作为函数指针
- 类模板参数推导失败会导致替换失败
- C++ 带有 decltype 的 SFINAE:替换失败成为错误?
- 折叠表达式模板参数推导/替换失败
- 使用"std::function"和先前推断的模板参数替换失败 - 为什么?
- 模板参数推导/替换失败 C++
- 当Boost ::绑定模板函数时,模板参数扣除/替换失败
- SFINAE使用演绎,但用替换失败
- 为什么代码中的模板参数推导/替换失败?-.
- GCC 模板参数推断/替换失败
- 为什么模板参数推导/替换失败
- 模板模板参数的替换失败
- C++模板参数推导/替换失败
- C++模板参数推导/替换失败:
- 使用类型名参数时,模板参数推导/替换失败
- 有没有办法将模板的替换失败转换为布尔值(真/假)或标签(标准::true_type/标准::false_type)
- 模板参数扣除/替换使用Lambda表达式使用高阶函数失败