C++ 代码类型替换失败

c++ code type substition fail

本文关键字:失败 替换 类型 代码 C++      更新时间:2023-10-16

我有这段代码,但不可能用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>
{
};