如何访问头文件中类的组件并打印其地址?

问题描述 投票:0回答:2

我开始学习C ++中的多重继承,我想从头文件中打印出类组件的地址。

原始头文件定义了几个类:

#include <iostream>
#include <iomanip>
class Account
{
  public:
  Account() {}
  unsigned long A1;
};

class Employee : public Account
{
 public:
 Employee() {}
 unsigned long E1;
};
class Student : public Account
{
 public:
 Student() {}
 unsigned long S1;
};
class Work_Study : public Employee, public Student
{
  public:
  Work_Study() {}
  unsigned long W1;
};

cpp文件在下面:

Work_Study Obj_WS; // declare a Work_Study object;
Work_Study * Obj_WS_ptr = &Obj_WS; 
int main() {

    std::cout << "Employee Account" << &((Account *) Obj_WS_ptr->A1) << std::endl;
    std::cout << "Employee" << &((Employee *) Obj_WS_ptr->E1) << std::endl;
    std::cout << "Student Account" << &((Account *) Obj_WS_ptr->A1) << std::endl;
    std::cout << "Student" << &((Student *) Obj_WS_ptr->S1) << std::endl;
    std::cout << "Work_Study" << &(Obj_WS_ptr->W1) << std::endl;
    return 0;
 }

当前存在两个错误:

第一个是关于对这些组件的模棱两可的请求。

Test_MI.cpp:12:51: error: request for member ‘A1’ is ambiguous

以及以下说明:

note: candidates are: long unsigned int Account::A1 unsigned long A1;

我应该在cpp文件中再次声明该类吗?还是有其他方法?

另一个是:左值,必须为一元'&'操作数。由于组件都是long unsigned int,此错误意味着什么?

在此多重继承中,有两个Account for Employee和Student,因此,如果要访问Student帐户,则需要强制转换指针以对其进行访问,因为内存布局首先是左侧,首先访问Employee对象。

c++ multiple-inheritance
2个回答
0
投票

(Account *) Obj_WS_ptr->A1是不明确的,因为Work_Study有2个Account实例,因此有2个A1成员-一个从Employee继承而另一个从Student继承。为了让编译器知道您要访问哪个Account,从而知道哪个A1,您必须执行以下任一操作:

  • 将类型转换更改为使用Employee*Student*而不是Account*(并使用static_cast,以便更容易阅读类型转换,并使编译器更安全地解析它们:]]]
std::cout << "Employee Account" << &(static_cast<Employee*>(Obj_WS_ptr)->A1) << std::endl;
std::cout << "Student Account" << &(static_cast<Student*>(Obj_WS_ptr)->A1) << std::endl;

Live Demo

  • 限定完全不使用任何类型转换的情况下访问哪个变量:
std::cout << "Employee Account" << &(Obj_WS_ptr->Employee::A1) << std::endl;
std::cout << "Student Account" << &(Obj_WS_ptr->Student::A1) << std::endl;

Live Demo

替代方法是使用virtual inheritance

class Account
{
public:
  Account() {}
  unsigned long A1;
};

class Employee : public virtual Account
{
public:
  Employee() {}
  unsigned long E1;
};

class Student : public virtual Account
{
public:
  Student() {}
  unsigned long S1;
};

class Work_Study : public Employee, public Student
{
public:
  Work_Study() {}
  unsigned long W1;
};

Live Demo

这样,即使AccountWork_Study都从Employee派生,所以Student中将仅存在1 Account,从而解决了您的类正在创建的所谓"diamond problem"


0
投票

这不是答案,只是让我无法发表评论。当我自己运行程序并在这里看到它时,我注意到多重继承演示输出的数字彼此不相等。我想我要问的是,如何使价值学生=学生账户价值而雇员=员工账户= work_study成为可能?

© www.soinside.com 2019 - 2024. All rights reserved.