C++:对象的隐式赋值
C++: Implicit assignment for Objects
我已经为我的问题寻找了很长时间,但我还没有找到任何令人满意的答案。问题很简单:当我对对象使用隐式赋值时,应该在括号之间放什么。
我一直习惯于看到这样的事情:分配一个int,你给它一个int值
class Point2D
{
private:
int m_nX;
int m_nY;
public:
// A specific constructor
Point2D(int nX, int nY)
: m_nX(nX), m_nY(nY) // So the int m_nX gets the int-value nX
{
}
}
但最近我发现了一个教程,其中参数被赋予了一个对象。(http://www.learncpp.com/cpp-tutorial/102-composition/)
class PersonalComputer
{
private:
CPU m_cCPU;
Motherboard m_cMotherboard;
RAM m_cRAM;
public:
PersonalComputer::PersonalComputer(int nCPUSpeed, char *strMotherboardModel, int nRAMSize)
: m_cCPU(nCPUSpeed), m_cMotherboard(strMotherboardModel), m_cRAM(nRAMSize)
// So the m_cCPU-object is given a parameter nCPUSpeed, and not another m_cCPU-object
{
}
};
所以我的问题是:隐式赋值是如何为对象工作的?以及如何将对象本身分配给对象(例如,将m_cCPU2-对象赋予m_cCPU-Object)。
感谢
这被称为初始化(而不是"隐式赋值")。
对于基元类型,这意味着对象被赋予初始值
int nX(5);
对于类类型,这意味着用这些参数调用类的构造函数:
Motherboard m("ABCDE");
要用初始化器列表中的另一个对象分配一个初始化对象,您需要定义一个复制构造函数
class CPU
{
CPU(const CPU& other)
: someSpeedVariable(other.someSpeedVariable) // Eg.
{}
}
然后你可以在其他课程中这样做。
class PC
{
PC(const CPU& cpu)
:m_cpu(cpu)
{}
CPU m_cpu;
}
我想这就是你要问的?
相关文章:
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- 如何动态地为对象中的数据赋值?
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- 为什么可以使用已删除的移动构造函数和赋值运算符移动对象?
- 构造函数对象赋值是否泄漏内存
- 为什么对象可以"moved"甚至缺少移动构造函数和移动赋值运算符?
- 在C++中,当表达式涉及对象时,将表达式赋值到对象中时,是否有定义的操作顺序?
- 复制 CTOR 与赋值运算符以初始化对象(性能)
- 是否可以在C++(17)中捕获某些对象属性的破坏性赋值事件
- 具有临时对象的 Fundamenta 数据类型赋值运算符
- 如何重载 const 对象的 [],以便值赋值不会导致编译错误
- 为什么参数可以在对象初始化时通过赋值运算符传递给构造函数?
- C++ 指针赋值运算符重载(不仅是对象赋值,还有指针赋值)
- 使用赋值运算符功能按距离对数组对象进行排序
- 将派生类对象赋值和访问到基类 "pointer to pointer" C++ 中的对象
- 赋值运算符是否应观察赋值对象的右值?
- C++ 矢量从构造函数赋值对象,无需临时
- 通过引用赋值对象,而不复制
- 在c++中创建一个赋值对象
- 子函数中的已赋值对象未在父函数中更新