struct定义在.h还是.cpp
时间: 2023-12-04 17:03:22 浏览: 29
struct的定义通常放在.h文件中,因为.h文件通常是用来声明和定义类、结构体、函数等的头文件,而.cpp文件则是用来实现这些声明和定义的源文件。这样做可以使得.h文件更加清晰明了,方便其他文件引用和调用。同时,如果将struct的定义放在.cpp文件中,那么其他文件将无法访问这个定义,这也是不可取的。
相关问题
在一个.h中定义全局结构体,在当前.cpp文件使用时无需重新声明
可以在.h文件中定义全局结构体,然后在需要使用该结构体的.cpp文件中包含该.h文件即可直接使用,无需重新声明。例如,在mystruct.h文件中定义一个结构体:
```
struct MyStruct {
int num;
char str[100];
};
```
然后在mystruct.cpp文件中包含该头文件,即可直接使用该结构体:
```
#include "mystruct.h"
void foo() {
MyStruct myStruct;
myStruct.num = 10;
strcpy(myStruct.str, "hello");
}
```
遍历链表.h文件和.cpp用case输出应该怎么写?
下面是遍历链表的.h和.cpp文件的代码,可以使用switch case语句输出:
链表头文件 LinkedList.h:
```c++
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
struct Node {
int data;
Node* next;
};
class LinkedList {
public:
LinkedList();
~LinkedList();
void insert(int value);
void remove(int value);
void print();
private:
Node* head;
};
#endif // LINKEDLIST_H
```
链表源文件 LinkedList.cpp:
```c++
#include "LinkedList.h"
LinkedList::LinkedList() {
head = nullptr;
}
LinkedList::~LinkedList() {
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
void LinkedList::insert(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = head;
head = newNode;
}
void LinkedList::remove(int value) {
Node* current = head;
Node* previous = nullptr;
while (current != nullptr) {
if (current->data == value) {
if (previous == nullptr) {
head = current->next;
} else {
previous->next = current->next;
}
delete current;
return;
}
previous = current;
current = current->next;
}
}
void LinkedList::print() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
```
使用switch case输出链表.h和.cpp文件的代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream hFile("LinkedList.h");
std::ifstream cppFile("LinkedList.cpp");
std::string line;
int fileIndex = 0;
while (getline(hFile, line)) {
switch (fileIndex) {
case 0:
std::cout << "// 链表头文件 LinkedList.h:" << std::endl;
break;
case 1:
std::cout << "// 链表源文件 LinkedList.cpp:" << std::endl;
break;
}
std::cout << line << std::endl;
if (line.find("#endif") != std::string::npos) {
++fileIndex;
}
}
while (getline(cppFile, line)) {
switch (fileIndex) {
case 1:
std::cout << "// 链表头文件 LinkedList.h:" << std::endl;
break;
case 2:
std::cout << "// 链表源文件 LinkedList.cpp:" << std::endl;
break;
}
std::cout << line << std::endl;
if (line.find("void LinkedList::print()") != std::string::npos) {
++fileIndex;
}
}
hFile.close();
cppFile.close();
return 0;
}
```
其中,fileIndex变量表示当前正在处理的文件的索引。当读取到`.h`文件的`#endif`预处理指令时,fileIndex加1,表示开始读取`.cpp`文件;当读取到`.cpp`文件的`void LinkedList::print()`函数定义时,fileIndex再次加1,表示`.cpp`文件处理完毕。在switch case语句中,根据fileIndex的值输出对应的注释和代码。