相关疑难解决方法(0)

声明和定义之间使用const限定符不一致

我注意到可以const在函数声明中出现值参数的限定符,然后在定义中省略.这不会改变函数的签名.它实际上编译得很好.

我还注意到常规类和模板类之间的行为是不同的.GCC和Clang的处理方式也有区别.

请考虑以下代码:

template <typename T> struct A {
    void f(const int);
};

template <typename T> void A<T>::f(int x) {
    x = 0;
}

struct B {
    void f(const int);
};

void B::f(int x) {
    x = 0;
}

void f() {
    A<float> a;
    a.f(0);

    B b;
    b.f(0);
}
Run Code Online (Sandbox Code Playgroud)

当我使用GCC编译时,我没有错误.有了Clang我得到:

test.cpp:10:7: error: read-only variable is not assignable
    x = 0;
    ~ ^
test.cpp:26:7: note: in instantiation of member function 'A<float>::f' requested here
    a.f(0);
      ^
Run Code Online (Sandbox Code Playgroud)

海湾合作委员会在定义中优先考虑限定词.Clang使用了声明,仅用于模板类A.

我的问题是: …

c++ gcc clang

15
推荐指数
1
解决办法
887
查看次数

标签 统计

c++ ×1

clang ×1

gcc ×1