将结构传递给头文件中的函数

Passing a struct to a function in a header file

本文关键字:文件 函数 结构      更新时间:2023-10-16

当我将函数打印放在指针结构中时.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);
}