gpt4 book ai didi

C++ 类、构造函数和函数

转载 作者:行者123 更新时间:2023-11-28 02:59:34 25 4
gpt4 key购买 nike

我刚刚开始学习 C++ 类、构造函数和函数,但如果我理解正确的话,我就不是这样了。我对代码没有问题,因为它工作正常,我只是对哪一位感到困惑,我在代码中添加了我认为正确的注释。如果有人可以解释我是错的还是对的,我将不胜感激。谢谢。

这是 Main.cpp,我理解是完整的文件:

  #include "Something.h"
#include <iostream>
using namespace std;

int main(){
Something JC;
system("PAUSE");
return 0;
}

这是 Something.cpp:

   #include "Something.h"
#include <iostream>
using namespace std;

//Something is the class and :: Something() is the function?

Something::Something()
{
cout << "Hello" << endl;
}

这是 Something.h:

   // this is a class which is not within the main.cpp because it is an external class? 

#ifndef Something_H
#define Something_H

class Something{
public:
Something(); //constructor?
};

#endif

我只是想了解哪一位是哪一位,如果我错了,那就是。

最佳答案

  1. 您通常在头文件中定义类,就像您在 Something.h 中所做的那样,以便许多 .cpp 文件可以包含此头文件并使用类(class)。

  2. 构造函数是一个特殊的函数,其名称与其所属的类相同。所以 Something 的构造函数也称为 Something

    class Something { // Class definition
    public:
    Something(); // Constructor declaration
    };
    Something::Something() // Constructor definition
    {
    cout << "Hello" << endl;
    }

    构造函数声明只是说 Something 的构造函数存在,不带任何参数。它实际上并没有实现它。任何包含 Something.h.cpp 文件都不需要知道实现,只需要知道它存在即可。相反,实现在 Something.cpp 中给出。

    因为构造函数定义写在类定义的外面,你需要说它属于Something。为此,您可以使用嵌套名称说明符 Something:: 对其进行限定。也就是说,Something::foo 表示 Something 类中的 foo,因此 Something::Something 表示Something 的构造函数。

关于C++ 类、构造函数和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21175312/

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