Skip to content
Discussion options

You must be logged in to vote

首先,在 C++ 里,你可以把 struct 看作一种特殊的 class。

然后,一个比较基础的编程实践是,把类型的定义放在 .h

// A.h
class A{
public:
    int f(int x, int y);
}

然后在 .cpp 实现定义。

// A.cpp
#include "A.h"
int A::f(int x, int y){
    return x + y;
}

如果你有一个工具类,在多个文件中都会使用,那么可以加上一个宏定义,使得不同文件的相同#include在展开的时候不会产生冲突(从楼上的实例文章复制过来的):

//item.h

#ifndef __ITEM_H__   // if item.h hasn't been included yet...
#define __ITEM_H__   //   #define this so the compiler knows it has been included

class Item { };

#endif 

// a.h
#include "item.h"

// b.h
#include "item.h"

// main.cpp
#include "a.h"
#include "b.h" // works well

在用 Visual Studio 的时候,可能会给你自动生成一个#pragma once。这个效果和上面是差不多的,但是可能在别的系统下编译的时候不支持。使用哪种就取决于你了。

Replies: 3 comments 4 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@liusy58
Comment options

liusy58 Feb 21, 2022
Collaborator

Comment options

You must be logged in to vote
3 replies
@Price1999a
Comment options

@Price1999a
Comment options

@VansamaZWT
Comment options

Answer selected by RicoloveFeng
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants