gpt4 book ai didi

一些构造函数代码之间的 C++ 区别

转载 作者:行者123 更新时间:2023-11-28 00:22:15 30 4
gpt4 key购买 nike

代码是什么:

class Time {
private:
int hours;
int minutes;
int seconds;
public:
Time() { hours = 0; minutes = 0; seconds = 0; }
};

不同于:

class Time {
public:
Time();

private:
int hours;
int minutes;
int seconds;
};

Time::Time() {
hours = 0;
minutes = 0;
seconds = 0;
}

抱歉,如果问题过于简单,但我是 C++ 的新手。我运行了这两个代码,但没有发现任何区别...

最佳答案

class Time {
private:
int hours;
int minutes;
int seconds;
public:
Time() { hours = 0; minutes = 0; seconds = 0; }
};

此代码声明并定义了 Time 类的默认构造函数。

class Time {
public:
Time();

private:
int hours;
int minutes;
int seconds;
};

Time::Time() {
hours = 0;
minutes = 0;
seconds = 0;
}

此代码在类定义中声明了 Time 类的默认构造函数,然后在类定义之外对其进行了定义。通常两者会被分成Time.hTime.cpp,如下所示:

Time.h

class Time {
public:
Time();

private:
int hours;
int minutes;
int seconds;
};

时间.cpp

#include "Time.h";

Time::Time() {
hours = 0;
minutes = 0;
seconds = 0;
}

关于一些构造函数代码之间的 C++ 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26921858/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com