简体   繁体   English

将字符串分配给 char 数组与 struct function

[英]Assigning string to char array vs. struct function

Okay so I know that the following doesn't work.好的,所以我知道以下内容不起作用。 I can't declare a char array, and then assign it later as follows.我不能声明一个 char 数组,然后按如下方式分配它。

char a[20]; 
a = "Hello World"; //SYNTAX ERROR

cout << a; 

However, when I use a struct data type, it seems like I can assign a char array after it's been initialized.但是,当我使用 struct 数据类型时,似乎我可以在初始化后分配一个 char 数组。

#include <iostream>
using namespace std;

struct Student 
{
    char name[10]; 
}

int main()
{
   Student student1; 
   student1 = {"Will"};

   cout << student1.name; 
}

This prints out: Will打印出来:Will

Why does this work?为什么这行得通?

The 2nd code works because a temporary is being initialized by Aggregate Initialization , and then that temporary is assigned to student1 , which copies each member's value.第二个代码有效,因为Aggregate Initialization正在初始化一个临时对象,然后将该临时对象分配给student1 ,它会复制每个成员的值。

A simple struct like you have has aggregate initialization and is trivially copyable.像您这样的简单结构具有聚合初始化并且可以轻松复制。 So when you write所以当你写

student1 = {"Will"};

a temporary object Student is created via aggregate initialization and then the copy assignment operator is called.通过聚合初始化创建一个临时的 object Student ,然后调用复制赋值运算符。

But what you should be using is std::string .但是您应该使用的是std::string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM