在另一个类中使用一个类对象

Using a class object in another class

本文关键字:一个 对象 另一个      更新时间:2023-10-16

Node Class

作为树实现的一部分,您应该实现一个 Node 类。每个节点都应包含一个 Customer 对象、指向左右子节点的指针以及(可选(父节点。

所以,目前我有一个客户类,这样:

class Customer {
public:
    Customer(void);
    Customer(string,char,int);
};

在我的节点类中,如何在链接两个文件时创建客户对象?

我是否只在节点头文件中包含以下内容?

#include "Customer.h"
class Node {
public:
    //Customer class
    class Customer {
    public:
        Customer(void);
        Customer(string,char,int);
    }
Node(void); //default constructor
Node(string,char,int); //Node constructor with customer details
Node* left;
Node* right;
Node* parent;
};

在节点.cpp文件中,要将值传递给节点:

//Constructor
Node::Node(string x, char y, int z) {
        lastName = x;       
        firstInitial = y;   
        balance = z;        
}

如何将客户对象的值传递给节点构造?

我是否只在节点头文件中包含以下内容?

不。您只需在 Node 中使用

类型为 Customer 的对象。
#include "Customer.h"
class Node {
   public:
      Node(void); //default constructor
      Node(string,char,int); //Node constructor with customer details
      Node* left;
      Node* right;
      Node* parent;
      Customer customer;
};

将构造函数实现为:

Node::Node() : left(nullptr),
               right(nullptr),
               parent(nullptr),
               customer() {}
Node::Node(string x, char y, int z) : left(nullptr),
                                      right(nullptr),
                                      parent(nullptr),
                                      customer(x, y, z) {}

您只需像以前一样包含标头,然后在 Node 类中声明一个 Customer 对象(私有/受保护/公共,如您所愿(。当您声明 Node 对象时,构造的第一件事是类中的对象,然后才是类本身。因此,如果您在两个构造函数中都有一个具有类名的cout,则当您声明 Node 对象时,您将看到:

客户的构造函数节点的构造函数

此外,如果要指定如何在 Node 构造函数中构造 Customer 对象,可以使用初始化列表

class Node
{
public:
    Customer obj;
    Node(string,char,int);
}

然后在.cpp文件中定义 Node 构造函数,如下所示:

Node :: Node(string x,char y,int z) : obj(x, y, z) {
}

这只是一个例子。您可以在初始化obj时使用静态值,也可以获取 Node 构造函数等的更多参数。

相关文章: