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

时间:2014-01-16 23:49:31

标签: c++ function class constructor

我刚刚开始学习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 

我只是想了解哪个位是哪个,如果我错了。

2 个答案:

答案 0 :(得分:1)

class-body中的

Something();是构造函数的声明(声​​明有一个),而

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

是构造函数的定义(说,它的作用)。您的程序可以具有相同功能的多个声明(特别是这也适用于构造函数),但只有一个定义。 (内联函数有一个例外,但这里不适用)。

答案 1 :(得分:1)

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

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

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

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

    中给出

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

相关问题