gpt4 book ai didi

c++ - 构造函数定义和声明不匹配

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:55:57 26 4
gpt4 key购买 nike

我有以下 C++ 代码,其中声明中构造函数的参数与构造函数的定义具有不同的常量性。

//testClass.hpp
class testClass {
public:
testClass(const int *x);
};

//testClass.cpp
testClass::testClass(const int * const x) {}

我能够使用 g++ 在没有警告的情况下编译它,这段代码应该编译还是至少给出一些警告?事实证明,64 位 solaris 上的内置 C++ 编译器给了我一个链接器错误,这就是我注意到存在问题的方式。

在这种情况下匹配参数的规则是什么?这取决于编译器吗?

最佳答案

在这种情况下,声明 允许省略 const 说明符,因为它不会为调用者改变任何内容。

它只对实现细节的上下文有影响。这就是为什么它出现在定义而不是声明

例子:

//Both f and g have the same signature
void f(int x);
void g(const int x);

void f(const int x)//this is allowed
{
}

void g(const int x)
{
}

任何调用 f 的人都不会关心您是否将其视为 const,因为它是您自己的变量拷贝。

和int * const x一样,都是你的指针拷贝。你是否可以指向其他东西对调用者来说并不重要。

如果您在 const int * const 中省略了第一个 const,那么这会有所不同,因为如果您更改它指向的数据,这对调用者很重要。

引用:C++ 标准,8.3.5 第 3 段:

"Any cv-qualifier modifying a parameter type is deleted ... Such cv-qualifiers affect only the definition of the parameter with the body of the function; they do not affect the function type"

关于c++ - 构造函数定义和声明不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/706059/

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