|
此文章由 rogerk 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 rogerk 所有!转贴必须注明作者、出处和本声明,并保持内容完整
原帖由 juncom 于 2010-8-4 20:34 发表 [url=http://www.oursteps.com.au/bbs/redirect.php?Question: Which of the following statements regarding functions' default arguments in C++ are correct?
A. Default arguments cannot be of pointer type.
B. Default arguments cannot be of a user-defined type.
C. Default arguments can never precede non-default arguments.
D. Default arguments exist in the global heap and not on the function's stack.
E. Default arguments are not considered for generating the function's signature.
C应该是对的。但不确定D和E。it doesn't make sense to store default arguments in global heap. 而E含意不清,不知它是仅指default values还是整个参数定义。defualt values 不会被包含在signature中。但the type of dafault argument 应该包括在signature中。
D说的不确切,所以也是不对的。default value其实无所谓在哪里,只要你在声明函数的时候能够访问到就可以了。这个value可以存在在static data里,也可以在heap里,但是不能是stack上的值,因为这样没法声明。stack上的值一般是在一个scope里面,但是default argument value你在声明函数的时候就应该能够访问,所以,至少没有简单直接的办法这么做。
随便写了点例子给你看看:
// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//value in static data
static int static_value = 10;
void foo (int i, int j = static_value)
{
printf("%d, %d\n", i, j);
}
//object in static data
class StaticClass
{
public:
int value;
StaticClass(int value)
{
this->value = value;
}
};
static StaticClass static_class(20);
void foo1 (int i, StaticClass& s = static_class)
{
printf("%d, %d\n", i, s.value);
}
//object in global heap as default argument
static StaticClass* static_class_heap = new StaticClass(30);
void foo2 (int i, StaticClass* s = static_class_heap)
{
printf("%d, %d\n", i, s->value);
}
// using member variable as default value is NOT permitted.
// Also, since declaring function inside function is not allowed,
// I am not aware of any way to use stack value as default argument value since you must have access to the default value when you
// declare the function.
class StackClass
{
public:
int value;
StackClass(int value)
{
this->value = value;
}
// error C2648: 'StackClass::value' : use of member as default parameter requires static member
//void foo(int i, int j = value)
//{
// printf("%d, %d\n", i, j);
//}
};
int _tmain(int argc, _TCHAR* argv[])
{
foo(5);
foo1(6);
foo2(7);
//StackClass s(40);
//s.foo(5);
return 0;
}
[ 本帖最后由 rogerk 于 2010-8-6 09:37 编辑 ] |
|