首页 > 解决方案 > 修改结构中的数据时遇到问题

问题描述

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

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;

标签: c++

解决方案


只有左值可以被赋值。这意味着只允许左值位于表达式的左侧。在修改对象之前,您必须知道对象在哪里。左值可以被认为是地址本身,尽管这可能会导致左值和指针之间的混淆。

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;

在上面的例子中xyz是左值。另一方面,表达式 : 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;奏效。


推荐阅读