CPP/C 中的常量用法和结构构造函数中的澄清

const in cpp/c usage and clarification in struct constructor

本文关键字:结构 构造函数 常量 CPP 用法      更新时间:2023-10-16

我想澄清一下

struct Sphere
{
    int a;
    Sphere()  {}
    Sphere(int given)
    {
        a = given;
    }
    Sphere (const Sphere &s)
    {
        a=s.a;
    }
};

当我这样做时:

 Sphere mySphere;
 mySphere.a = 5;

调用哪个构造函数?const在这里的作用是什么?如果我省略const构造函数,则不会分配 a 的值。为什么?

调用哪个构造函数?

默认构造函数。

常量在这里的作用是什么?

都不是。

如果我省略 const 构造函数,则不会分配 a 的值。为什么?

我不知道,这没有意义。

您没有使用复制构造函数。完全。

您所做的只是默认构造一个Sphere然后分配给其数据成员。