#include<iostream>
class ravi
{
private:
char a[10],char b[10];
public:
void setdata(char x[10],char y[10])
{
a = x; b = y;
}
void show()
{
std::cout << a << b;
}
};
int main()
{
ravi r;
r.setdata("text","copied");
r.show();
}
我正在尝试复制字符串&#34; text&#34; &#34;复制&#34;到x和y,我得到一个错误,#char;从char *到char&#34;的分配不兼容。有人告诉我我的代码有什么问题。
答案 0 :(得分:7)
C ++中的字符串是std::string
。您正在使用字符数组,即C字符串,NUL终止字符串等,这些字符串更难操作。
只需替换a
和b
的类型(以及对setdata
的参数的微小改进,您就可以获得一些有用的功能,以及string
的一些有用功能:
#include <string>
class ravi
{
std::string a;
std::string b;
public:
void setdata(const char* x, const char* y)
{
a = x;
b = y;
}
void show()
{
std::cout << a << b;
}
};
如果可以(关于ravi
的API),请尝试使用std::string const&
代替const char*
:
void setdata(std::string const& x, std::string const& y)
使用C ++ 17,您最好使用std::string_view
代替const char*
参数类型:
void setdata(std::string_view x, std::string_view y)
答案 1 :(得分:3)
数组没有复制赋值运算符。所以这些陈述
a=x;b=y;
无效。
您应该使用标头strcpy
中声明的标准C函数strncpy
或<cstring>
来复制字符数组。 C ++中的字符串文字也有常量字符数组的类型。因此,应使用限定符setdata
声明成员函数const
的参数。
void setdata( const char x[], const char y[] )
{
strncpy( a, x, sizeof( a ) );
a[sizeof( a ) - 1] = '\0';
strncpy( b, x, sizeof( b ) );
b[sizeof( b ) - 1] = '\0';
}
考虑到此声明无效
char a[10],char b[10];
要么你应该写
char a[10]; char b[10];
或
char a[10], b[10];
答案 2 :(得分:0)
使用strcpy
中的string.h
功能:
#include <string.h>
void setdata(char x[10],char y[10])
{
strcpy(a,x);
strcpy(b,y);
}