declaration vs. definition
A declaration introduces a name – an identifier – to the compiler. It tells the
compiler “This function or this variable exists somewhere, and here is what it should
look like.” A definition, on the other hand, says: “Make this variable here” or
“Make this function here.” It allocates storage for the name. This meaning works whether
you’re talking about a variable or a function; in either case, at the point of definition
the compiler allocates storage. For a variable, the compiler determines how big that
variable is and causes space to be generated in memory to hold the data for that variable.
For a function, the compiler generates code, which ends up occupying storage in memory.
1.对于函数,
声明如:int func(int);定义则是:
int func(int x)
{
...
}
2.对于变量
变量的声明是告诉编译器这个变量在别的地方已经定义了,并且它是某某类型。如:
extern int a;
而定义:
int a;//将为变量a分配空间
void (*funcPtr)();
When you are looking at a complex definition like this, the best way to attack it is to
start in the middle and work your way out. “Starting in the middle” means starting at
the variable name, which is funcPtr. “Working your way out” means looking to the right
for the nearest item (nothing in this case; the right parenthesis stops you short), then
looking to the left (a pointer denoted by the asterisk), then looking to the right (an
empty argument list indicating a function that takes no arguments), then looking to the
left (void, which indicates the function has no return value). This right-left-right m
otion works with most declarations.
头文件的内容
There are certain issues that you must be aware of in order to organize your code properly
and write effective header files. The first issue concerns what you can put into header
files. The basic rule is “only declarations,” that is, only information to the compiler
but nothing that allocates storage by generating code or creating variables. This is
because the header file will typically be included in several translation units in a
project, and if storage for one identifier is allocated in more than one place, the linker
will come up with a multiple definition error (this is C++’s one definition rule: You can
declare things as many times as you want, but there can be only one actual definition for
each thing).
default constructor
如果一个类没有构造函数,那么编译器会为这个类提供一个默认的构造函数(无参数)用于定义该类
的对象,如果用户定义了构造函数,那么这个默认构造函数不再存在。例:
class test
{
private:
int i;
}
上例中无构造函数,编译器提供default ctor,所有test类的对象均由default ctor定义,而
class test
{
private:
int i;
public:
test(int ii);
}
那么所有的test类对象都使用test(int ii)初始化,如
test hi(0);
而
test hi;将产生编译错误,因为default ctor已经不存在,编译器依旧调用test(int ii)初始化,
此时由于参数不匹配出错。
chap1--chpa7
最新推荐文章于 2022-03-11 01:27:23 发布