这是我简单的代码来说明。在类中有一本书具有作者作为数据成员。
我想从测试程序中修改作者的邮件,但是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", "[email protected]");
   john.print();  // [email protected]

   Book cppbook("C++ Introduction", john);
   cppbook.print();

   cppbook.getAuthor().setEmail("[email protected]");
   cppbook.print(); //mail doesn't change: C++ Introduction - [email protected]
   cppbook.setAuthorMail("[email protected]");
   cppbook.print(); //mail changes: C++ Introduction - [email protected]
}


最佳答案

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


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

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

关于c++ - C++。更改对象数据成员的数据成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37843412/

10-12 01:33