在类中存储指针

Edu*_*Edu 0 c++ variables pointers class

我正在学习C++并且遇到指针问题.
这个简单的项目包含一个发票,其中包含指向客户的指针.

类别:

class Customer {
    string name;
public:
    Customer(string name) { this->name = name; };
    string getName() { return name; };
    void changeName(string name) { this->name = name; };
};

class Invoice {
    Customer * customer;
public:
    Invoice(Customer *customer) { this->customer = customer; };
    Customer getCustomer() { return *customer; };
};
Run Code Online (Sandbox Code Playgroud)

主要:

Customer *customer1 = new Customer("Name 1");
Invoice invoice1(customer1);

cout << invoice1.getCustomer().getName() << endl; //Return:Name 1;
Run Code Online (Sandbox Code Playgroud)

如何使用Customer :: changeName(字符串名称)才能使其工作:

(...) changeName("Name 2");

cout << invoice1.getCustomer().getName() << endl; //Return:Name 2;
Run Code Online (Sandbox Code Playgroud)

我不知道应该用什么来改变顾客的名字.或者也许我在班级发票中做错了.

为什么要通过Invoice更改名称?
所以我可以学习如何在项目开始变大之前学习如何使用指针.
稍后我将会有一个发票矢量和一个客户矢量.从发票或客户向量中获取指向客户的指针应该是相同的.

谢谢你,
爱德华多

Car*_*bou 7

Customer getCustomer() { return *customer; };
Run Code Online (Sandbox Code Playgroud)

应该

Customer& getCustomer() { return *customer; };
Run Code Online (Sandbox Code Playgroud)

因为在第一种情况下,您复制客户对象,因此您的更改发生在一个被丢弃的临时对象中...

在第二个中,您将返回对您创建的对象的引用.

改名

string newName = "Edu";
invoice1.getCustomer().changeName( newName );
Run Code Online (Sandbox Code Playgroud)