gpt4 book ai didi

c++ - 使用 CRTP 访问基类的 protected 成员

转载 作者:太空狗 更新时间:2023-10-29 20:40:12 25 4
gpt4 key购买 nike

我想问你一个关于CRTP的问题。假设您有一个基类和一个派生类,如下所示。有没有办法在派生类的一个成员函数(例如“foo”)中从基类中提取成员“值”?

编译器告诉我: 错误:“值”未在此范围内声明

#include <iostream>

template <class T, class Implementation>
class FooBase
{
protected:
void fooBase(void) {};
int value;
};

template <class T>
class Foo : public FooBase <T, Foo<T>>
{
friend FooBase <T, Foo<T>>;

public:
void foo()
{
std::cout << "Its own value is : " << value << std::endl;
}
};

int main ()

{
Foo <int> foo;
foo.foo();

return 0;
}

最佳答案

因为您直接继承自依赖于 T 的基类,所以您需要使用 this-> 来访问您的数据成员:

std::cout << "Its own value is : " << this->value << std::endl;
// ^^^^^^

关于c++ - 使用 CRTP 访问基类的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25100541/

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