将结构传递给头文件中的函数
Passing a struct to a function in a header file
当我将函数打印放在指针结构中时.cpp与其他所有内容一起工作正常,但是当我尝试将函数分离到头文件中时,我不再能够找出问题所在。任何想法都会很棒。
指针结构.cpp
#include<iostream>
#include<string.h>
#include "pointerStru.h"
using namespace std;
struct student
{
char name[20];
int num;
float score[3];
};
int main()
{
struct student stu;
PointerStru pstttt;
stu.num=12345;
strcpy(stu.name,"li li");
stu.score[0]=67.5;
stu.score[1]=89;
stu.score[2]=78.6;
pstttt.print(&stu);
}
//pointerStru.h
#ifndef PointerStru_H_INCLUDED
#define PointerStru_H_INCLUDED
#include <iostream>
using namespace std;
class PointerStru{
private:
public:
void print(struct student *p)
{
cout << "*p " << p << endl;
cout<<p->num<<"n"<<p->name<<"n"<<p->score[0]<<"n"
<<p->score[1]<<"n"<<p->score[2]<<"n";
cout<<" ";
}
};
#endif // PointerStru_H_INCLUDED
在标头中使用 struct student
之前未定义定义。要么将其包含在标头中,要么将其向前声明为不透明结构并在.cpp文件中定义PointerStru::print
的实现(在定义struct student
之后)。
在不相关的说明中,头文件中的using namespace std;
是错误和邪恶的。永远不要这样做。
如果你把打印方法的定义放在头文件中,那么编译器只知道学生是一个结构体(从打印参数列表中,当它被声明为结构时),但不知道这个结构是如何定义的(定义在后面的 cpp 文件中)。在这种情况下,编译器将其视为不完整的类型并引发错误。
如果您在学生结构定义下面的 cpp 文件中定义打印方法,编译器将能够编译代码(在打印方法显示之前,它知道如何定义学生结构)。
你可以这样使用它
//pointerStru.h
#ifndef PointerStru_H_INCLUDED
#define PointerStru_H_INCLUDED
#include <iostream>
struct student;
class PointerStru{
private:
public:
void print(struct student *p);
};
#endif // PointerStru_H_INCLUDED
#include<iostream>
#include<string.h>
#include "pointerStru.h"
using namespace std;
struct student
{
char name[20];
int num;
float score[3];
};
void PointerStru::print(struct student *p)
{
cout << "*p " << p << endl;
cout<<p->num<<"n"<<p->name<<"n"<<p->score[0]<<"n"
<<p->score[1]<<"n"<<p->score[2]<<"n";
cout<<" ";
}
int main()
{
struct student stu;
PointerStru pstttt;
stu.num=12345;
strcpy(stu.name,"li li");
stu.score[0]=67.5;
stu.score[1]=89;
stu.score[2]=78.6;
pstttt.print(&stu);
}
相关文章:
- C++ gmock - 我们如何在单元测试 cpp 文件中读取/获取 cpp 文件函数的参数值
- 使用其他头文件函数的头文件
- 创建文件函数是否可以打开仅在WinObj实用程序中的全局目录下列出的设备的句柄?
- 如何指定创建文件函数获取未缓存的结果?
- 标准库头文件函数原型的实现是如何用 c++ 编写的?
- 如何将类对象作为对另一个头文件函数的引用传递
- 读取文件函数lpbuffer和字节以读取澄清
- C++ - 未定义的对多个文件函数的引用
- 使用C++的可视 Unicode 文件函数
- C 创建文件函数错误
- WinAPI 创建文件函数 2.
- 具有CREATE_ALWAYS处置的创建文件函数
- 重写c库文件函数
- 如何使用客户端调用堆栈中的地址从 PDB 检索文件/函数/行号?
- 通过头文件函数将遍历的数据从二进制搜索树加载到Vector中
- 需要帮助无法弄清楚为什么我的头文件函数声明不起作用
- 是否可以在不使用文件函数的情况下使用代码块从文件运行某些用例测试?
- 如何用c++文件函数读写8位整数单位形式的数据
- 在c++中读文件函数如何识别文本文件的结束
- 使用Windows API的c++文件函数