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

How to access to the components of class in header file and print their addresses?

本文关键字:组件 打印 地址 何访问 访问 文件      更新时间:2023-10-16

我开始学习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 文件中再次声明该类吗?还是有其他办法?

另一个是:需要作为一元"&"操作数的左值。当组件长时间无符号 int 时,此错误意味着什么?

在此多重继承中,有两个员工帐户和学生帐户,因此如果我们想访问学生帐户,我们需要强制转换指针来访问它,因为内存布局首先是左侧,首先访问员工对象。

>(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;

现场演示

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

现场演示

另一种方法是改用虚拟继承

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;
};

现场演示

这样,即使EmployeeStudent都来自AccountWork_Study中也只有 1 个Account存在,从而解决了您的类正在创建的所谓"钻石问题"。