所以我有这段代码:
class xx
{
int getnum(); //Is this a forward declaration or a prototype declaration and why?
};
int xx::getnum()
{
return 1+3;
}
这个问题在代码中已经进行了评论,但是:
int getnum();
是前向声明还是原型声明,为什么?
所以我有这段代码:
class xx
{
int getnum(); //Is this a forward declaration or a prototype declaration and why?
};
int xx::getnum()
{
return 1+3;
}
这个问题在代码中已经进行了评论,但是:
int getnum();
是前向声明还是原型声明,为什么?
C++只允许函数进行完整的原型声明,与C不同,例如int getnum();
在C中可以是int getnum(int);
的前向声明。
C.1.7 Clause 8: declarators [diff.decl]
8.3.5 Change: In C ++ , a function declared with an empty parameter list takes no arguments. In C, an empty parameter list means that the number and type of the function arguments are unknown.
Example:
int f(); // means int f(void) in C ++, int f( unknown ) in C
Rationale: This is to avoid erroneous function calls (i.e., function calls with the wrong number or type of arguments).
Effect on original feature: Change to semantics of well-defined feature. This feature was marked as “obsolescent” in C.
Difficulty of converting: Syntactic transformation. The function declarations using C incomplete declaration style must be completed to become full prototype declarations. A program may need to be updated further if different calls to the same (non-prototype) function have different numbers of arguments or if the type of corresponding arguments differed.
前向声明是一种声明类型,其中您为变量、常量、类型或函数指定标识符,而不给出其实现。它实际上告诉编译器有关具有某些元数据(如名称、大小等)的实体。
另一方面,通过原型声明函数意味着声明具有名称和类型签名的函数,而不指定函数体。因此,它仅适用于函数概念,而不适用于变量、常量或类型。因此,前向声明可以被视为原型声明的超集。
对于上述示例,根据定义,它既是前向声明又是原型声明。希望我没有错。
int getnum(); // Function prototype. You have not yet implemented the body of getnum() function, thus its a forward delcaration.
class RandomClass; // Forward declaration of RandomClass. You have not yet implemented this class but you need it for the rest of your code.
class xx{
RandomClass *foo; // Our need of having a member like that, made us make a forward declaration of the class RandomClass, above class xx
void BarFunction(); // Function Prototype!
};
int getnum(){ //This is the simply the body of your prototype above. Has nothing to do with the classes
return 1+3;
}
void BarFUnction(){
cout << "foo-bar\n" ;
}