这是我用来说明的简单代码。有一本 Book 的 Author 作为类内部的数据成员。 我想从测试程序修改作者的邮件,但 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
}
最佳答案
I want to modify the mail from the Author from the test program, but
cppbook.getAuthor().setEmail("...")
doesn't work.
Author getAuthor();
应该是 Author& getAuthor();
如果你想更改关联到 Book
的内部对象.
否则,您只是在更改 Author
的临时拷贝实例。
关于C++。更改对象数据成员的数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843412/