c++ - 错误 : expression must be a modifiable lvalue

标签 c++ struct

我收到一个错误:

expression must be a modifiable lvalue at line, obj.name = ptr->name

我试过像这样使obj成为数组类型的对象

 for(int j=0 ;j<1;j++)
{
obj[j].id = ptr->id;
obj[j].balance= ptr->balance;
obj[j].name = ptr->name;   //still getting error here.
obj[j].nic = ptr->nic;
}
return(obj);
}

但这也没有用。

如果我注释掉错误并只传递三个剩余值,它应该可以工作,但我在第一个输出后收到垃圾值。

原代码如下:

#include<iostream>
using namespace std;

struct bank
{
  int id, nic;
  float balance;
  char name[20];


};
bank search(bank* );

void main()

{

    bank data[2],mobj;
    for(int i=0;i<2;i++)
    {
    cout<<"enter name: ";
    cin>>data[i].name;
    cout<<"enter id: ";
    cin>>data[i].id;
    cout<<"enter balance : ";
    cin>>data[i].balance;
    cout<<"enter nic : ";
    cin>>data[i].nic;

    }


    mobj=search(data);

    cout <<"balance of customer no. "<<mobj.balance<<endl;
    cout<<"id is" <<mobj.id<<endl;
    cout<< "nic is"<<mobj.nic<<endl;



    system("pause");
}




bank search(bank *ptr)
{   
    int id;
    cout<<"enter value you want to serch"<<endl;
    cin>>id;
    bank obj;
for(int i=0 ; i<2 ;i++)
{
    if(ptr->id == id)
    {
        break;
    }
    ptr++;
}

obj.id = ptr->id;
obj.balance= ptr->balance;
obj.name = ptr->name;    //error in this line(obj must be modifiable value)
obj.nic = ptr->nic;

return(obj);
}

请在您认为合适的时候提供帮助!

最佳答案

obj.name 是一个char 数组。您不能对数组进行赋值。所以如果你想坚持使用数组:

  1. 参见 c++ array assignment of multiple values
  2. 使用 strcpy(obj.name, ptr->name);

但我建议转换为 std::string ...它比数组更容易使用,在我看来你打算使用 obj.name 作为字符串。所以得到了正确的字符串。

关于c++ - 错误 : expression must be a modifiable lvalue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25381071/

相关文章:

c++ - Ubuntu 14 中 QtCreator [Yocto Image] 的交叉编译错误

c++ - 这个声明作为英文句子的确切含义是什么?

c - 函数 typedef 和从 C 中的结构调用函数

C++11 使用指针修改 initializer_list 中的元素导致 SIGSEGV,为什么?

c++ - std::endl 的值是否取决于操作系统?

c - 双指针: pointer to struct member that is a pointer

c++ - C++中的初始化结构错误

c++ - 将不正确的值类型分配给结构属性时出现笑脸!

c - typedef struct 和 extern 声明的未知类型名称错误 - C 语言

c++ - 什么是关于国际化和本地化的良好介绍和教程?