C .更改对象数据成员的数据成员

C++. Change data member of an Object data member

本文关键字:数据成员 对象      更新时间:2023-10-16

这是我要说明的简单代码。有一本书在班上有一个作者作为数据成员。我想从测试程序中修改作者的邮件,但是cppbook.getauthor()。setemail(" ...")不起作用。我尝试通过引用传递。我找到了一种选择,但不满意。一定是一个简单的答案,我想我想念一些东西。

class Author {
private:
    string name;
    string email;
public:
    Author(string name, string email) {
       this->name = name;
       this->email = email;
    }
    string getName() {
       return name;
    }
    string getEmail() {
       return email;
    }
    void setEmail(string email) {
       this->email = email;
    }
    void print() {
       cout << name << "-" << email << endl;
    }
};

class Book {
private:
   string name;
   Author author; // data member author is an instance of class Author
public:
    Book(string name, Author author)
          : name(name), author(author) {
    }
    string getName() {
       return name;
    }
    Author getAuthor() {
       return author;
    }
    void print() {
       cout << name << " - " << author.getEmail() << endl;
    }

    void setAuthorMail(string mail) {
       author.setEmail(mail);
    }
};

int main() {
   Author john("John", "john@gmail.com");
   john.print();  // John-john@gmail.com
   Book cppbook("C++ Introduction", john);
   cppbook.print();
   cppbook.getAuthor().setEmail("peter@gmail.com");
   cppbook.print(); //mail doesn't change: C++ Introduction - john@gmail.com
   cppbook.setAuthorMail("andrew@gmail.com");
   cppbook.print(); //mail changes: C++ Introduction - andrew@gmail.com
}

实时示例

我想从测试程序中修改作者的邮件,但cppbook.getAuthor().setEmail("...")不起作用。

Author getAuthor();如果要更改与Book关联的内部对象,则应为Author& getAuthor();

否则,您只是更改该Author实例的临时副本。

您是按值返回对象,而不是通过引用。这意味着,您获得了作者的 copy ,但您没有修改存储在书类中的一个。

您应该修改

中的签名
Author& Book::getAuthor();

要更改对象作者有效