相关疑难解决方法(0)

为什么我的对象不能访问公共基类中定义的另一个对象的受保护成员?

以下代码生成编译器错误:

'BaseTest :: _ protMember':无法访问类'BaseTest'中声明的受保护成员

为什么我不能访问我的成员变量_protMember,class SubTest即使它受到保护?

class BaseTest
{
public:
    BaseTest(){};

    BaseTest(int prot)
    {
        _protMember = prot;
    };

protected:
    int _protMember;
};

class SubTest : public BaseTest
{
    // followup question
    SubTest(const SubTest &subTest)
    {
        _protMember = subTest._protMember; // this line compiles without error
    };

    SubTest(const BaseTest &baseTest)
    {
        _protMember = baseTest._protMember; // this line produces the error
    };
};
Run Code Online (Sandbox Code Playgroud)

后续问题:

为什么在添加的拷贝构造函数中我可以访问另一个实例的受保护成员

c++

7
推荐指数
2
解决办法
3805
查看次数

派生类如何使用基类的受保护成员?

假设基类A定义了一个受保护的成员。派生类B使用此成员。

class A
{
public:
  A(int v) : value(v) { }

protected:
  int value;
};

class B : public A
{
public:
  B(int v) : A(v) { }
  void print() const;
  void compare_and_print(const A& other) const;
};
Run Code Online (Sandbox Code Playgroud)

该函数B::print只获取当前成员的值并打印它:

void B::print() const
{
  std::cout << "Value: " << value << "\n";
}
Run Code Online (Sandbox Code Playgroud)

另一个成员函数 ,B::compare_and_print采用 的实例A,检查它们的值并打印两者的最大值:

void B::compare_and_print(const A& other) const
{
  auto max_value = std::max(value, other.value);
  std::cout << "Max value: " …
Run Code Online (Sandbox Code Playgroud)

c++ protected private-members

5
推荐指数
1
解决办法
649
查看次数

标签 统计

c++ ×2

private-members ×1

protected ×1