如何在源文件C++中创建构造函数
How to create a constructor in source file C++
我已经研究了几个小时。这个简单的任务让我难以理解...
鼓励任何重构建议。我显然不是一个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.
};
相关文章:
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 通过构造函数创建的所有对象都具有相同的向量
- 除了构造函数之外,还创建 QLabel
- 通过构造函数创建一些值并尝试添加到文档中使用 rapidjson 不起作用
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 创建一个没有复制构造函数的类的 std::vector 的 std::vector
- 在没有默认构造函数的情况下创建的派生对象
- 创建类类型的动态分配数组,其中类不得具有默认构造函数
- 用于创建命名构造函数的宏
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 在 c++ 中,如果我创建一个接受一个具有默认值的参数的构造函数 - 它会用作默认(空)构造函数吗?
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- C++递归地在类构造函数中创建对象
- 在C++中为结构(联合)创建构造函数
- 创建构造函数时没有适当的默认构造函数可用
- 如何为指针成员创建构造函数
- 继承链是否创建构造函数调用链?
- GCC 4.2.x创建构造函数
- 创建构造函数引用全局变量的类的全局实例时,C++ 程序崩溃