构造函数将所有值设置为0

PKP*_*hon -3 c++ oop constructor private

因此,根据我从学校的作业,我必须创建一个默认构造函数,它应该将所有浮点数和整数设置为0,所有字符串都设置为"NA".

之前很容易我只需要做一个构造函数来将音量设置为0,将卡路里设置为0等等.

我的问题是,

如何设置所有浮点数,并将ints设置为0并尝试将字符串全部设置为"NA"?

这是我到目前为止所做的

class Candy {
private:
    float sweetness;

protected:
    string color;

//CONSTRUCTOR//

    void setName(string n);

    void setFloat(float f);

    void setInt(int i);
Run Code Online (Sandbox Code Playgroud)

这是我们要做的另一个cpp文件.

Candy::Candy() {

Candy(string n) {
    setName(n);
}

Candy bo("NA");
}
Run Code Online (Sandbox Code Playgroud)

我是朝着正确的方向吗?我对此真的很陌生,而且我的语法也不是很好.谢谢!

Jes*_*uhl 8

使用构造函数初始化列表:

class Candy {
private:
    float sweetness;

protected:
    string color;

public:
    Candy() : sweetness(0.0f), color("NA") { }
};
Run Code Online (Sandbox Code Playgroud)

或者(在C++ 11或更高版本中),使用类内初始值设定项:

class Candy {
private:
    float sweetness = 0.0f;

protected:
    string color = "NA";

public:
    Candy() = default;
};
Run Code Online (Sandbox Code Playgroud)