Loading

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++

posted @ 2024-04-26 11:04  记录学习的Lyx  阅读(5)  评论(0编辑  收藏  举报