.h和.cpp文件中的默认参数 [英] default parameters in .h and .cpp files

查看:286
本文介绍了.h和.cpp文件中的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

COMPILER:: g ++ 4.7.2

好的.因此,我对.h.cpp文件中的默认参数感到困惑.在许多地方(包括此站点)都提到默认参数只能在.h文件中添加,而不能在.cpp文件中添加. 但是,这段代码证明了它是错误的:

Ok. So I am confused about default parameters in .h and .cpp files. It is mentioned in many places( including this site) that default parameters can be added only in .h files and not in .cpp files. However, this code proves it wrong:

test1.h

#pragma once

#include <iostream>
using namespace std;

class Class{
public:
    Class(int, int, int=1);
};

test1.cpp

#include "test1.h"

Class::Class(int a, int b=2, int c)
{
    cout<<a<<" "<<b<<" "<<c<<endl;
}

int main()
{
    Class a(1);
    return 0;
}

现在,根据我的测试,可以将默认参数添加到.cpp文件中.但是,以下限制适用:

Now, according to what I have tested, default parameters can be added to .cpp files. However, the following restrictions hold:

  1. .cpp.h文件中存在的默认参数不应 重叠.即Class(a, b, c=1)(在.h文件中)和 Class::Class(a,b,c=2)(在.cpp文件中)无效.

  1. The default parameters present in .cpp and .h file should not overlap. i.e. Class(a, b, c=1) (in .h file) and Class::Class(a,b,c=2)( in .cpp file) is invalid.

一个众所周知的规则是,一旦默认参数被设置为 添加,此后声明的所有变量也必须包含 默认值.我们称其为 defpara 规则.现在,

It is a well known rule that once default parameters have been added, all the variables declared after that must also contain default values. Lets call this the defpara rule. Now,

在函数声明(.h文件)中声明的变量应 遵守 defpara 规则,即Class(a, b=2, c)(在.h文件中)为 无效,无论.cpp文件中声明了什么.

The variables stated in the function declaration( .h file) should obey the defpara rule i.e. Class(a, b=2, c) (in .h file) is invalid irrespective of what's declared in .cpp file.

如果认为变量具有默认值(作为 .h.cpp文件中的默认值的交集), 遵循 defpara 规则.即Class(a, b, c=1)(在.h文件中)和 Class::Class(a,b=2,c)(在.cpp文件中)有效.但是Class(a, b, c=1)(在.h文件中)和Class::Class(a=2,b,c)(在.cpp文件中)是 无效.

If one considers the variables having default values (as an intersection of default values in .h and .cpp files), it would follow the defpara rule. i.e. Class(a, b, c=1) (in .h file) and Class::Class(a,b=2,c)( in .cpp file) is valid. But Class(a, b, c=1) (in .h file) and Class::Class(a=2,b,c)( in .cpp file) is invalid.

所以...我是对,错...

So....I am right, wrong???

推荐答案

这仅适用于您,因为您的主要功能也位于您的test.cpp文件中,因此它会看到您的类的实现中指定的默认参数.如果将main函数放在仅包含test.h的单独文件中,则该代码将无法编译.

This only works because your main function is also in your test.cpp file, so it sees the default argument specified in your class' implementation. If you put your main function in a separate file that only includes test.h, this code will not compile.

另一种查看方式是,当其他一些包含test.h时,代码所看到的只是在test.h中声明的内容,因此将不使用放置在其他位置的默认参数.

Another way of looking at it is, when some other includes test.h, all that code sees is what is declared in test.h, so default arguments put elsewhere will not be used.

这篇关于.h和.cpp文件中的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆