C++声明和定义的区别
定义和声明#
在学习C\C++的过程中有两组概念需要注意:声明(declarartion)和定义(definition)。引用Declare vs Define in C and C++上的一段话:
A declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored.
- 声明就是说明一个符号的类型、名字;
- 定义就是提供一个符号的所有细节(包括类型、名字)。
- 函数定义:说明函数是做什么的
- 类定义:说明类包含的字段(field)、方法(method)
- 变量定义:说明变量分配多大空间、分配在哪
可以认为定义包含了声明,但声明没有包含定义
A declaration of a built-in type such as int is automatically a definition because the compiler knows how much space to allocate for it.
内置类型的声明(declaration)会自动变成定义(definition),比如int类型,因为编译器知道为它分配多大的空间
int i; //声明,但是自动变成定义
int j = 10; //声明,但是自动变成定义
extern int k; //有extern关键字,是声明
enum fruit{ apple = 1, banana, pear }; //声明且定义枚举类型
//声明且定义Person类
class Person{
private:
const string name;
public:
Person(const string& sname) : name(sname) { ... }//初始化参数列表
Person(); //default constructor
Person(const Person&);
virtual ~Person();
}
void func(int i); //声明
void func(int i){ //定义
cout << i <<endl;
}
参考链接#
Declarations and definitions (C++)
Declare vs Define in C and C++
作者:qianxiaohan
出处:https://www.cnblogs.com/qianxiaohan/p/18159559
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具