gpt4 book ai didi

c++ - 如何在继承类成员函数中访问基类成员的地址?

转载 作者:行者123 更新时间:2023-11-30 03:39:02 25 4
gpt4 key购买 nike

<分区>

我最近进入了 C++ 类、继承和模板的整个世界。但是我卡住了。请建议我解决此问题的方法。

#include <iostream>

using namespace std;

template <typename type>
class a
{
protected:
type *b;
};

template <typename type>
class p : public a<type>
{
public:
void f()
{
type **q = &a<type>::b;
cout << *q << endl; // some other code in reality related to (*q)
}
};

int main()
{
p<int> obj;
obj.f();
return 0;
}

但是结果不成功:

x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:9:9: error: ‘int* a<int>::b’ is protected
type *b;
^
x.cpp:18:16: error: within this context
type **q = &a<type>::b;
^
x.cpp:18:26: error: cannot convert ‘int* a<int>::*’ to ‘int**’ in initialization
type **q = &a<type>::b;
^

所以我转换了type **q = &a<type>::b;type* a<type>::* q = &a<type>::b; .然后我得到了一个额外的错误:

x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:9:9: error: ‘int* a<int>::b’ is protected
type *b;
^
x.cpp:18:26: error: within this context
type* a<type>::* q = &a<type>::b;
^
x.cpp:19:13: error: invalid use of unary ‘*’ on pointer to member
cout << *q;
^

所以我转换了bpublic: class a的成员来自 protected: .但这也给了我一个错误:

x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:19:13: error: invalid use of unary ‘*’ on pointer to member
cout << *q;
^

现在我无法进行进一步的修改。我很想知道原始代码是否没有篡改类的 protected 特性。

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