为什么我不能直接分配一个数组变量给另一个数组变量的'='操作? [英] Why can't I assign an array variable directly to another array variable with the '=' operator?

查看:314
本文介绍了为什么我不能直接分配一个数组变量给另一个数组变量的'='操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想说,我知道的Java pretty好了,现在我缓慢而稳步地学习C ++,请与我裸露,因为我敢肯定,这是给你的知识渊博的计算器家伙琐碎的问题。

为什么以下分配不工作?我想如果可能的话一个低级别的解释。此外,这里的编译器错误,我得到:在'字符*'的分配不兼容的类型为CHAR [20]

 类UCSDStudent {  焦炭名[20];  上市:    UCSDStudent(CHAR名称[]){
      //这个 - > NAME =名称;不行!请解释原因
      strcopy(本 - >副本,复印件); //作品
    }};


解决方案

由于当你有一个函数调用像这样 UCSDStudent(字符名称[])只的ADRESS数组名称复制而不是整个数组。它是一个C \\ C ++功能。

此外,名称定义为字符名称[20] 不是修改的左值。

关于的strcpy :它会带来不确定的behaivour好像你的源阵列没有一个NULL字符会复制一些垃圾桶这个 - >名称太。你可以阅读更多关于的strcpy 这里

So I'd like to say I know Java pretty well, and now I'm slowly but surely learning C++ so please bare with me because I'm sure this is a trivial question for you knowledgeable stackoverflow guys.

Why does the following assignment not work? I would like a low-level explanation if possible. Also, here's the compiler error I get: incompatible types in assignment of 'char*' to 'char [20]'

class UCSDStudent {

  char name[20];

  public:

    UCSDStudent( char name[] ) {
      //this-> name = name; does not work! Please explain why not
      strcopy( this -> copy, copy ); //works 
    }

};

解决方案

Because when you have a function call like this UCSDStudent( char name[] ) only the adress of the array name is copied instead of the whole array. It is a C\C++ feature.

Furthermore the name defined as char name [20] is not a modifiable lvalue.

Regarding strcpy: it will bring undefined behaivour as if your source array doesn't have a NULL character it will copy some trash to this->name too. You may read more about strcpy here

这篇关于为什么我不能直接分配一个数组变量给另一个数组变量的'='操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆