如何访问头文件中类的组件并打印它们的地址?
How to access to the components of class in header file and print their addresses?
我开始学习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;
};
现场演示
这样,即使Employee
和Student
都来自Account
,Work_Study
中也只有 1 个Account
存在,从而解决了您的类正在创建的所谓"钻石问题"。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 如何将 txt 文件中的行分隔为组件C++
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 如何访问头文件中类的组件并打印它们的地址?
- 为什么RGB组件被打印为符号,直到我添加+'0'-'0'?
- 在C++中打印列表元素的组件
- 我试图打印强连接的组件,但我一直得到内存错误