【问题标题】:C++ classes, constructors and functionsC++ 类、构造函数和函数
【发布时间】:2014-01-16 23:49:30
【问题描述】:

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

这是 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 

我只是想知道哪个是哪个,如果我错了。

【问题讨论】:

    标签: c++ function class constructor


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

    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::fooSomething类内部表示foo,因此Something::Something表示Something的构造函数。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2017-01-21
        • 2014-05-27
        • 1970-01-01
        • 1970-01-01
        • 2011-04-03
        • 2010-12-16
        • 2016-02-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多