gpt4 book ai didi

c++ - g++编译错误 "... is protected from within this context",而clang没有错误

转载 作者:IT老高 更新时间:2023-10-28 21:57:36 30 4
gpt4 key购买 nike

我有以下代码:

#include <iostream>

class BaseClass {
protected:
static int x;
};

int BaseClass::x;

class DerivedA: public BaseClass {
public:
DerivedA() {
x = 3;
}
};

class DerivedB: public BaseClass {
public:
DerivedB() {
std::cout << DerivedA::x;
}
};

int main(int argc, char* argv[]) {
DerivedB b;
}

使用 g++ 编译 (g++ classtest.cpp) 我收到以下错误:

classtest.cpp: In constructor ‘DerivedB::DerivedB()’:
classtest.cpp:9:5: error: ‘int BaseClass::x’ is protected
int BaseClass::x;
^ classtest.cpp:25:32: error: within this context
std::cout << DerivedA::x;

当我使用 clang++ (clang++ classtest.cpp) 编译时没有错误。

为什么 g++ 返回编译错误?

我使用 g++ 5.1.0 版和 clang++ 3.6.1 版

最佳答案

GCC 错误。 [class.access.base]/p5:

A member m is accessible at the point R when named in class N if

  • m as a member of N is public, or
  • m as a member of N is private, and R occurs in a member or friend of class N, or
  • m as a member of N is protected, and R occurs in a member or friend of class N, or in a member of a class P derived from N, where m as a member of P is public, private, or protected, or
  • there exists a base class B of N that is accessible at R, and m is accessible at R when named in class B.

NDerivedAmxR 是构造函数DeriveddB。存在 DerivedA 的基类 BaseClass,可在 R 访问,x 在类 中命名BaseClass(即,BaseClass::x)可以在 R 上清楚地访问,所以到第四个要点,DerivedA::x 可通过 R 访问。

关于c++ - g++编译错误 "... is protected from within this context",而clang没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31389470/

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