gpt4 book ai didi

c++ - 在 gcc 中编译时出错

转载 作者:行者123 更新时间:2023-11-28 00:10:45 25 4
gpt4 key购买 nike

我正在为我的类(class)做一个项目,讲师给了我们一些代码片段,我们被要求修改它。代码在我的 Visual Studio 类计算机中正确编译,但是当我尝试使用 gcc 编译它时,它给了我一个错误。我得到的错误是:

||=== Build: Debug in Project (compiler: GNU GCC Compiler) ===|
/home/nitin/Read.h|45|error: declaration of ‘std::vector<rv> rvs::rv’ [-fpermissive]|
/home/nitin/Read.h|35|error: changes meaning of ‘rv’ from ‘struct rv’ [-fpermissive]|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

错误的代码片段是:

struct rv
{
double val, prob;
rv(const double v, const double p): val(v), prob(p) {};
};


struct rvs
{
int row_n, col_n;
vector<rv> rv;
rvs(const int r=-2, const int c=-2): row_n(r), col_n(c) {};
};

你能告诉我可能是什么问题吗?

最佳答案

您的声明违反了以下规则

3.3.7 Class scope [basic.scope.class]

1 The following rules describe the scope of names declared in classes.

...

2) A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

在 vector 声明点rv 指的是类型struct rv。但是当在完整类rvs 的范围内重新求值时,它指的是类成员rvs::rv。这种不一致是 C++ 中的错误。

标准中的示例说明了类似的错误

enum { i = 1 };

class X {
char v[i]; // error: i refers to ::i
// but when reevaluated is X::i
...
enum { i = 2 };
};

正如@Ben Voigt 在评论中所述,如果您明确解决 rv as struct rvrv as 之间的冲突rvs::rv,错误将消失。您可以通过使用详尽的类型说明符 struct rv 或通过显式指定范围 ::rv 来实现。

请注意,这是编译器不保证/不需要捕获的错误之一。

关于c++ - 在 gcc 中编译时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33267529/

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