在另一个类中使用一个类对象
Using a class object in another class
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 构造函数等的更多参数。
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 从多个源构造一个对象,包括一个对象向量
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 检查哪个对象调用了另一个对象的对象方法
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 包装一个对象并假装它是一个 int
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- 如何使用函数将一个对象的输入复制到另一个对象中
- 选择一个元素而不是一个对象的数组的原因
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 打印对象的映射,其中另一个对象作为键
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 为什么将两个对象分配给另一个对象后,两个对象不一样?
- 绘制一个对象,比较模具缓冲区的两个不同值