c++ 中的 声明和定义 区别

       声明(declaration),指定了变量的类型与名称。声明的目的是为了让变量名对程序而言是已知的。

    定义(definition),不仅要指定变量的类型和名称,还要分配存储空间,甚至提供初始值。同时,定义也是声明

    既然变量定义已经包括变量声明的功能了,为何还要变量声明呢?

    存在变量声明是为了支持单独编译(separate compilation)。单独编译允许文件A中的代码能够使用在文件B中定义的变量mystring。声明的存在是为了告诉编译器:文件A中的变量mystring定义在了其他的文件中,请先编译文件A,待遇到变量mystring的定义后,再给文件A的变量mystring分配存储空间或赋值。

   举个例子:

    B.h

#include <iostream>
#include <string>
using  std::string;
void Printmsg(string x);

    B.cpp

#include <iostream>
#include "B.h"
extern string mystring;
extern string mystring2="error";
void Printmsg(string mystr){
    std::cout<<"你刚刚输入的是:"<<mystr;
}

    A.cpp

  

#include <iostream>
#include "B.h"
using namespace std;
string mystring="hello word";
//string mystring2="error0";

int main()
{
   Printmsg(mystring);
   return 0;
}



假如把A.cpp中mystring2注释去掉,将会出现什么情况呢?大家试试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值