C++:对象的隐式赋值

C++: Implicit assignment for Objects

本文关键字:赋值 对象 C++      更新时间:2023-10-16

我已经为我的问题寻找了很长时间,但我还没有找到任何令人满意的答案。问题很简单:当我对对象使用隐式赋值时,应该在括号之间放什么。

我一直习惯于看到这样的事情:分配一个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;
}

我想这就是你要问的?