gpt4 book ai didi

c++ - 在结构中修改数据时遇到问题

转载 作者:行者123 更新时间:2023-11-30 04:48:19 25 4
gpt4 key购买 nike

我正在尝试修改结构中的数据,但似乎无法正常工作。 如有必要,很乐意提供更多信息。

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作为左值,value of x作为右值。想到*p作为左值,value of *p作为右值。等等

int x, y;
int z = 2*x + 3*y;

在上面的例子中,x , yz是左值。另一方面的表达方式:2*x , 3*y , 甚至 (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;工作。

关于c++ - 在结构中修改数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com