gpt4 book ai didi

c++ - C++中接口(interface)文件和实现文件之间的显式函数区别

转载 作者:行者123 更新时间:2023-11-30 02:35:55 25 4
gpt4 key购买 nike

我对实现中的显式函数有疑问,接口(interface)文件是 C++。让我用一个例子来解释它。

接口(interface)文件:

#ifndef IntCell_H
#define IntCell_H
class IntCell{
public:
explicit IntCell(int initialValue =0);
int read() const;
void write( int x );
private:
int storedValue;
};
#endif

实现文件:

#include "IntCell3.h"

IntCell::IntCell(int initialValue)
:storedValue(initialValue) {}

int IntCell::read() const
{ return storedValue; }

void IntCell::write( int x )
{ storedValue = x ;}

在编写这些代码时,签名必须与我们在读取函数中看到的完全匹配(两者都是访问器)。我同意,但问题是为什么我不能写

IntCell::explicit IntCell(int initialValue) 

在实现文件中?我不能在这一行中添加“显式”一词的原因是什么?提前致谢。

最佳答案

因为这是规则。您只将 explicit 放在声明(标题)中。原因是因为实现仅通过声明在其他翻译单元中可见。所以如果声明在头部没有被标记为explicit,那么其他翻译单元就不能“知道”该函数被标记为explicit。并且因为将 explicit 放在实现文件中没有意义,语言的设计者决定它应该只在声明中使用。另一个原因是清晰度:为什么要在允许已经足够复杂的声明的语言中添加另一种无用的符号语法,例如:

void (*signal(int, void (*fp)(int)))(int);

关于c++ - C++中接口(interface)文件和实现文件之间的显式函数区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33311138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com