将字符串赋值给结构体'



我试图在main()中初始化数组,但我得到一个错误。代码是这样的:

#include<iostream>
#include<string.h>
using namespace std;
class word
{
public:
char str[20];
};
int main()
{
word a;
word b;
a.str[]="12345";
b.str[]="67";
}

'a'和'b'是类词的两个对象。

如果你使用的是C字符串,那么你需要复制它:

int main()
{
word a;
word b;
strncpy(a.str, "12345", sizeof(a.str));
strncpy(b.str, "67", sizeof(b.str));
}

如果你想更有效地使用c++,可以考虑使用std::string:

#include <iostream>
#include <string>
class word
{
public:
std::string str; // Embrace the std:: prefix, it's there for a reason
};
int main()
{
word a;
word b;
a.str = "12345";
b.str = "67";
}

现在赋值是超级简单的

注意:您的原始代码有语法错误,因为a.str[] = ...不是有效的c++。[]部分表示"未知/任意长度的数组";可以在函数签名中使用,但不能在赋值中使用。您可以执行a.str[n] = 'x',但它只分配一个字符。

我建议"封装"。
含义:保持数据成员私有;公开公共方法以访问私有数据成员(get和set)。
在可能的情况下,使用不可变数据(在构造时写入,永不更改)。
你可以在这里在线玩代码。

#include<iostream>
#include<string.h>
using namespace std;
class word
{
const string str;
public:
word(const string &w) : str(w) {}
word(const char *w)   : str(w) {}
const string & get() const { return str; }
};
int main()
{
word a("12345");
word b("67");
cout << "Word a = " << a.get() << endl;
cout << "Word b = " << b.get() << endl;
}

最新更新