当我将函数print连同其他所有内容一起放到pointerStruct.cpp中时,它可以正常工作,但是当我尝试将函数分离到头文件中时,我不再能够解决问题。任何想法都很棒。

pointerStruct.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;是对与错。永远不要做。

关于c++ - 将结构传递到头文件中的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19533176/

10-14 15:35