C++。更改对象数据成员的数据成员

标签 c++

这是我用来说明的简单代码。有一本 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
}

Live Example

最佳答案

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/

相关文章:

表示目录结构的 C++ TREE

c++ - 如何在 C++ 中将字符串的确切内容分配给 double

c++ - 相当于 int 的 typedef

c++ - 如何通过 getter 函数序列化包含指针的类?

c++ - C++11有规定静态/全局变量的构造顺序吗?

c++ - 多平台IDE

c++ - 通过COM将自定义接口(interface)类型的SAFEARRAY返回给VB6

c++ - 为什么可以使用额外参数调用 Boost.Bind 函数?

c++ - 以 qreal 引用作为参数的语法

c++ - 在客户端窗口 win32 c++ 中捕获图像