问题集--理解编译原理
想把类从主函数文件中分离出来:
编译时出现了undefied refenence to...问题,代码如下:
//main.cpp
#include <iostream>
#include "student.h"
int main(int argc, char **argv)
{
Student s1;
s1.setNum(100);
s1.display();
return 0;
}
//student.h
#ifndef STUDENT_H
#define STUDENT_H
class Student
{
private:
int num;
public:
void setNum(int n);
void display();
};
#endif
//student.cpp
#include "student.h"
#include <iostream>
void Student::setNum(int n)
{
num = n;
}
void Student::display()
{
std::cout << num << std::endl;
}
编译时出现以下错误:

如果将student.cpp中的函数放到类中,则不会出错!
//student.h
#ifndef STUDENT_H
#define STUDENT_H
class Student
{
private:
int num;
public:
void setNum(int n)
{
num = n;
};
void display()
{
std::cout << num << std::endl;
};
};
#endif
A:student.cpp要添加到当前项目里,和main.cpp一起编译成功以后,才能链接在一起生成目标程序!
由于编译时#include宏定义的头文件会全部被替换为源代码进行编译。如果将类代码全部放在.h文件中,由于main.cpp包含student.h头文件,在编译时会将.h头文件替换,再对main.cpp文件进行编译,这样不会出现编译错误!
学到即赚到。
浙公网安备 33010602011771号