gpt4 book ai didi

c++ - 在 C++ 中,是否可以从同级的第二个派生对象访问第一个派生对象的 protected 基础数据成员?

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

我正在编写一个 C++ 程序,其中我有两个来自基类的派生对象,例如 Derived_1 和 Derived_2。

在处理过程中,第一个对象调整基础数据成员(这里只是模拟使用 Derived_1 的默认构造函数)。然后我想做的是从 Derived_1 对象中读取该数据,并在 Derived_2 的构造函数中使用它来初始化 Derived_2 中的同一成员。

// -std=c++14
#include <iostream>

class Base {
public:
int data(void) { return data_; }

protected:
int data_{0};
};

class Derived_1 : public Base {
public:
Derived_1(void) { this->data_ = 42; }
};

class Derived_2 : public Base {
public:
// Derived_2(const Derived_1& a1) { this->data_ = a1.data_; }
};

int main() {
Derived_1 a1;
std::cout << "Derived_1 data: " << a1.data() << '\n';

// Derived_2 a2 = a1;
// std::cout << "Derived_2 data: " << a2.data() << '\n';
}

如果Derived_2中的构造函数没有被注释掉,就会出现这个错误:

In constructor ‘Derived_2::Derived_2(const Derived_1&)’:
error: ‘int Base::data_’ is protected within this context
Derived_2(const Derived_1& a1) { this->data_ = a1.data_; }
^~~~~

我在 SO 上查看了许多相关问题,试图找到解决方案,(例如) Access a derived private member function from a base class pointer to a derived objectWhy can I access a derived private member function via a base class pointer to a derived object?但如果我已经看过,我目前很难找到答案。可能只是我经验不足。

感谢您帮我解决这个问题。

最佳答案

是的,可以通过使 Derived_2 成为 Derived_1 friend :

class Derived_1 : public Base {
//This says that Derived_2 is a friend, which means that Derived_2
//can access every member in Derived_1
friend class Derived_2;
public:
Derived_1(void) { this->data_ = 42; }
};

现在你可以这样做了:

class Derived_2 : public Base {
public:
Derived_2(const Derived_1& a1)
{
//Legal, Derived_2 is a friend of Derived_1, so it can access the
//protected member 'data_'
this->data_ = a1.data_;
}
};

请注意,现在 Derived_2 可以修改 Derived_1每个 数据成员,而不仅仅是 data_

关于c++ - 在 C++ 中,是否可以从同级的第二个派生对象访问第一个派生对象的 protected 基础数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37864673/

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