声明与定义的区别

C++ 要求先声明后使用

声明不要求初始化。

定义必须初始化

做过单板开发的应该就能看懂下列程序,估计就想明白了。

#include <string>

void f(); // forward declaration

int main()
{
const double pi = 3.14; //OK
int i = f(2); //OK. f is forward-declared
std::string str; // OK std::string is declared in <string> header
C obj; // error! C not yet declared.
j = 0; // error! No type specified.
auto k = 0; // OK. type inferred as int by compiler.
}

int f(int i)
{
return i + 42;
}

namespace N {
class C{/*...*/};
}

程序参考来源:微软的C++开发文档 链接:https://docs.microsoft.com/en-us/cpp/cpp/declarations-and-definitions-cpp?view=msvc-160&viewFallbackFrom=vs-2019

如何还是不能理解的话,

想一下java开发的 import 关键字。

使用import导入其他包的时候,其实就是一次声明。告诉编译器,我使用了这个包里的函数,类,变量等等。

我们不需要知道这个包里函数,类,变量是怎么定义实现的,只需要知道包里有这些函数,类,变量的名称及使用方法即可。

 

posted @ 2021-06-06 16:58  神龙逗勇士  阅读(121)  评论(0编辑  收藏  举报