g++拒绝让我访问某种类型,只是因为它恰好是一个私人的祖父.这有意义吗?
struct A {};
struct B : private A {};
struct C : B {
void foo(A const& a) {}
};
Run Code Online (Sandbox Code Playgroud)
编译这会产生:
1:10: error: ‘struct A A::A’ is inaccessible
6:12: error: within this context
Run Code Online (Sandbox Code Playgroud)
我的观点是:我从不想A作为祖先访问.事实上,如果A是一个私人祖先B,不应该对任何人完全不可见,但B(即C)?
当然,我可以使用protected继承,但在我的情况下,它并没有真正意义.
为什么以下代码会遇到错误“ A”,而无法访问“ B”呢?这是我的想法:
每当我们调用函数foo()时,它将执行new B(5),它将首先调用其基本结构A的构造函数。
struct A的构造函数是一个公共方法,因此它的派生struct B应该可以访问它(如果我没有记错的话,应加以保护)。
然后将调用结构B的构造函数以创建具有五个0的向量。
然后删除对象a将调用析构函数B,然后调用析构函数A。
我的逻辑有什么问题吗?您的回答将不胜感激
#include <iostream>
#include <vector>
using namespace std;
struct A
{
A() { cout << "Constructor A called"<< endl;}
virtual ~A() { cout << "Denstructor A called"<< endl;}
};
struct B : private A
{
vector<double> v;
B(int n) : v(n) { cout << "Constructor B called"<< endl;}
~ B() { cout << "Denstructor B called"<< endl;}
};
int main()
{
const A *a = new …Run Code Online (Sandbox Code Playgroud) 我将我的 C++ 基类更改为protected继承,并且我的dynamic_cast(s) 停止工作。
为什么要改变继承来protected改变行为dynamic_cast?
struct Base {
static Base *lookupDerived(); // Actually returns a Derived * object.
};
struct Derived : protected /* Switch this to public to get it working */ Base {
static void test() {
Base *base = lookupDerived();
if (dynamic_cast<Derived *>(base)) {
std::cout << "It worked (we must be using public inheritance)." << std::endl;
} else {
std::cout << "It failed (we must be using protected inheritance)." …Run Code Online (Sandbox Code Playgroud) 我想了解访问修饰符关于继承的4种不同行为,当涉及使用和/或省略templates和this关键字的4种组合时.以下所有代码均在g ++ 4.8中完成:
这里有一个GrandChild类,它privateLY从继承Parent,这privateLY从继承GrandParent,其中有一个public enum n.非对象,客户端代码可以访问GrandParent::n,因为后者是一个public enum.但是GrandParent::n从内部无法进入GrandChild:
#include <iostream>
using namespace std;
struct GrandParent { enum {n = 0}; };
struct Parent : private GrandParent { enum {n = 1}; };
struct GrandChild : private Parent {
enum {n = 2};
void f() {cout << GrandParent::n << endl;}
// ^ error: 'struct GrandParent GrandParent::GrandParent'
// is …Run Code Online (Sandbox Code Playgroud)