在头文件 (.h) 中声明构造函数然后在类文件 (.cpp) 中定义的语法 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14574143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:27:45  来源:igfitidea点击:

Syntax of Declaring a Constructor in Header (.h) and then Defining in a Class File (.cpp) C++

c++constructor

提问by user2020058

If anyone could lay this out, I would appreciate it. Example of what I thought would work (assume the needed #include statements are there):

如果有人可以解决这个问题,我将不胜感激。我认为可行的示例(假设需要#include 语句):

//.h file
class someclass(){}

//.cpp
someclass::
    someclass(){
         //implementation
         // of 
         //class
};

回答by billz

someclass.h file

someclass.h 文件

#ifndef SOME_CLASS_H
#define SOME_CLASS_H    

class someclass
{
public:
  someclass();  // declare default constructor

private:
  int member1; 
};

#endif

someclass.cpp

某个类.cpp

someclass::someclass()   // define default constructor
: member1(0)             // initialize class member in member initializers list
{
   //implementation
}

回答by Billy ONeal

Header:

标题:

//.h file
class someclass
{
    someclass();
}; // <-- don't forget semicolon here

Source:

来源:

#include "someClass.h"
//.cpp
someclass::someclass()
{
    // Implementation goes here
} // <-- No semicolon here

回答by Andy Prowl

You have to declarethe constructor in your class if you want to provide a definitionfor it. You are only doing the second thing.

如果要为其提供定义,则必须在类中声明构造函数。你只是在做第二件事。

Also, your original class definition contains some mistakes: no parentheses are needed after the class name, and a semicolon is needed after the final curly brace.

此外,您的原始类定义包含一些错误:类名后不需要括号,最后一个大括号后需要分号。

class someclass
{
    someClass(); // Here you DECLARE your constructor
};

...

someclass::someclass() // Here you DEFINE your constructor
{
    ...
}