c++ - 修改结构中的数据时遇到问题
问题描述
我正在尝试修改结构中的数据,但似乎无法使其正常工作。如有必要,很高兴提供更多信息。
actTree 返回一个二叉搜索树。
findNode 返回该树上的一个节点。
Data() 返回actData。
```
struct actData
{
string year,award,winner,name,film;
};
```
void modifyActRecord() {
cout << "Enter the name of the film for the movie data you would like to modify:" << endl;
cin.ignore();
string s;
getline(cin, s);
cout << "Which field would you like to modify?" << endl;
cout << "Your choices are year, award, winner, name, film"
<< endl;
string f;
getline(cin, f);
if (f == "year") {
cout << "What would you like to change it to?" << endl;
string in;
getline(cin, in);
//line in question
actTree->findNode(s)->Data().year = in;
}
I can access the code fine with:
cout << actTree->findNode(s)->Data().year;
but cannot modify it with:
actTree->findNode(s)->Data().year = in;
解决方案
只有左值可以被赋值。这意味着只允许左值位于表达式的左侧。在修改对象之前,您必须知道对象在哪里。左值可以被认为是地址本身,尽管这可能会导致左值和指针之间的混淆。
int x; // x is an lvalue
int* p; // *p is an lvalue
int a[100]; // a[42] is an lvalue; equivalent to *(a+42)
// note: a itself is also an lvalue
struct S { int m; };
struct S s; // s and s.m are lvalues
struct S* p2 = &s; // p2->m is an lvalue; equivalent to (*p2).m
// note: p2 and *p2 are also lvalues
另一方面,右值是表达式的值。在上面的代码中,将其x
视为左值,将 thevalue of x
视为右值。将*p
其视为左值,并将 thevalue of *p
视为右值。等等
int x, y;
int z = 2*x + 3*y;
在上面的例子中x
,y
和z
是左值。另一方面,表达式 : 2*x
, 3*y
, even(2*x + 3*y)
都是右值。由于右值只是一个值,而不是值的位置,因此不能将其分配给,就像您不能说 2*x = 4 一样,因为它根本不正确。
因此,在您的示例中,data().year
它不是左值。所以它不能被分配,只能被使用。这就是原因,cout << actTree->findNode(s)->Data().year;
工作正常,但actTree->findNode(s)->Data().year = in;
没有,因为您可能正在返回actData
。您需要返回一个可修改的左值,这就是actData&
您的情况。
class Node
{
actData m_data;
public:
actData Data()
{
return m_data;//returning value of m_data, not the address
}
/*Change above function to below function*/
actData* Data()
{
return &m_data;//returning address here so that it can be modified
}
};
执行上述操作应该会actTree->findNode(s)->Data().year = in;
奏效。
推荐阅读
- python - 接收类型作为参数的 Python3 类装饰器隐式调用这些类型的构造函数
- python - 无法运行烧瓶服务器的 pyinstaller 可执行文件。ValueError:找不到语言“ru”的字典
- c++ - Visual Studio Code 中的详细模式构建 C/C++ 文件
- python - 在pycharm中调试pytorch代码(可行性)
- javascript - Chrome 的 javascript 调试器与互联网上大多数文章的对比?
- c++ - physx 多线程复制转换数据
- python - 字典中不存在键
- php - 在 php mysql 查询中转义撇号
- heroku - 嗨,我实际上试图在 heroku 上部署我的应用程序,它说构建成功,但是如果运行该链接,它会说应用程序错误。我使用 node.js
- database - 如何从不起眼的 Windows 7 程序中抓取数据?