对于大型项目,不能将所有代码都写到一个文件中。不同文件写不同的代码,可以修改和编译执行。(因为如果都写到一个文件中,每次修改一点点,就要所有代码重新编译)。
示例:
一个pencil类,一个Book类,还有一个SchoolBag类包含了Pencil类和Book类。
#include <iostream>
using namespace std;
class Pencil
{
public:
void setSize(int size)
{
p_size = size;
}
void inform()
{
cout << "this is pencil! " << endl;
}
int get_size()
{
return p_size;
}
private:
int p_size; // the size of pencil
};
class Book
{
public:
void setSize(int size)
{
b_size = size;
}
void inform()
{
cout << "this is a book! " << endl;
}
int get_size()
{
return b_size;
}
private:
int b_size;
};
class SchoolBag
{
public:
void set_info(int p_size, int b_size)
{
p.setSize(p_size);
b.setSize(b_size);
}
void show_info()
{
p.inform();
cout << "size = " << p.get_size() << endl;
b.inform();
cout << "size = " << b.get_size() << endl;
}
private:
Pencil p;
Book b;
};
int main()
{
SchoolBag s;
s.set_info(10,100);
s.show_info();
return 0;
}
pencil.h pencil.cpp
book.h book.cpp
school.h school.cpp
main.cpp
#pragma once
#include <iostream>
using namespace std;
class Pencil
{
public:
void setSize(int size);
void inform();
int get_size();
private:
int p_size; // the size of pencil
};
#pragma once
#include <iostream>
using namespace std;
class Book
{
public:
void setSize(int size);
void inform();
int get_size();
private:
int b_size;
};
#pragma once
#include "pencil.h"
#include "book.h"
class SchoolBag
{
public:
void set_info(int p_size, int b_size);
void show_info();
private:
Pencil p;
Book b;
};
#include "pencil.h"
void Pencil::setSize(int size)
{
p_size = size;
}
void Pencil::inform()
{
cout << "this is pencil! " << endl;
}
int Pencil::get_size()
{
return p_size;
}
#include "book.h"
void Book::setSize(int size)
{
b_size = size;
}
void Book::inform()
{
cout << "this is a book! " << endl;
}
int Book::get_size()
{
return b_size;
}
#include "schoolbag.h"
void SchoolBag::set_info(int p_size, int b_size)
{
p.setSize(p_size);
b.setSize(b_size);
}
void SchoolBag::show_info()
{
p.inform();
cout << "size = " << p.get_size() << endl;
b.inform();
cout << "size = " << b.get_size() << endl;
}
#include "schoolbag.h"
int main()
{
SchoolBag s;
s.set_info(10, 100);
s.show_info();
return 0;
}
Note:
注意运行的时候一定要把上面的七个文件进行“编译链接”比如放在visual studio里面之后,运行main可以自动实现上述功能。如果运行在dev cpp里面不编译链接,是无法运行的: