rav*_*ran -1 c++ arrays string setter class
#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();
}
Run Code Online (Sandbox Code Playgroud)
我试图将字符串"text""复制"复制到x和y,我收到一个错误"从char*到char的赋值不兼容".有人告诉我我的代码有什么问题.
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;
}
};
Run Code Online (Sandbox Code Playgroud)
如果这是可能的(关于API ravi),请尝试使用std::string const&以代替const char*:
void setdata(std::string const& x, std::string const& y)
Run Code Online (Sandbox Code Playgroud)
使用C++ 17,您最好使用std::string_view代替const char*参数类型:
void setdata(std::string_view x, std::string_view y)
Run Code Online (Sandbox Code Playgroud)