如何在源文件C++中创建构造函数

How to create a constructor in source file C++

本文关键字:创建 构造函数 C++ 源文件      更新时间:2024-09-24

我已经研究了几个小时。这个简单的任务让我难以理解...

鼓励任何重构建议。我显然不是一个C++的人。

我已经看过所有这些视频,但没有一个演示类有多个字段。我当然没有看到初始化空数组的源文件。

友情链接:
C++ - 类 - 创建源文件和头文件

Buckys C++ 编程教程 - 15 - 将类放在单独的文件中

C++头文件*

C++链接器的工作原理

C++中的构造函数

如何编写C++类

将C++类分成 .h 和 .cpp 文件

经过一些评论,我更新了问题的上下文

节点.h

#ifndef NODE_H_                                /* INCLUDE GUARD */
#define NODE_H_ 
#include <iostream>
namespace Node{
class Node {
private:                                       // PRIVATE FIELDS
static const int size = 27;
public:                                        // PUBLIC FIELDS
Node(bool isWord);                           // CONSTRUCTOR
bool isWord;
Node* character[size]{};
void insertme(std::string);                  // FUNCTION PROTOTYPE
int  searchme(std::string);                  // FUNCTION PROTOTYPE
};
}
#endif                                           // NODE_H_

节点.cpp

// SOURCE FILE
#include "Node.h"
#include <iostream>
using namespace std;
Node::Node(bool isWord) {
/*
* This constructor needs to:
* set isWord to false
* populate Node* character[size] to be filled with null
*/
};
void insertme(string token){
return;
}
int searchme(string token){
return 0;
}

注意:此构造函数不会抛出任何错误,但它不会以我需要的方式初始化成员字段

// SOURCE FILE
#include "Node.h"
#include <iostream>
using namespace std;
Node::Node(isWord) {};
void insertme(string token){
return;
}
int searchme(string token){
return 0;
}

如果您希望构造函数在没有参数的情况下可用,则需要为采用bool的构造函数声明默认值。没有任何强制参数的构造函数是默认构造函数。

类的定义及其成员函数的声明:

#pragma once // or a standard header guard
class Node {
public:
Node(bool isWord = false); // this is now a default constructor
// other members etc ...
};

它的可能用途:

#include "Node.h"              // where Node is defined
int main() {
Node x;                    // default construct a `Node`
}

Node.cpp中构造函数的定义:

#include "Node.h"
#include <ios>
#include <iostream>
Node::Node(bool isWord) {      // note, no default values here
std::cout << std::boolalpha << isWord << 'n';
}

输出(如果编译和链接):

false

演示

在头文件中,你创建了一个没有变量的函数原型。

public:                                        // PUBLIC FIELDS
Node();                                      // CONSTRUCTOR

这将使类使用不执行任何操作的默认构造函数。

相反,您需要在头文件中定义一个带有布尔参数的构造函数。

public:                                        // PUBLIC FIELDS
Node();                                      // CONSTRUCTOR
Node(bool);                                  // CONSTRUCTOR 2

您还需要确保在 .cpp 文件的 Node 构造函数的函数定义中包含正确的类型。

Node::Node(bool isWord)  {
// DO SOMETHING.
};