【发布时间】:2012-11-29 02:50:06
【问题描述】:
您好,我目前遇到一个问题,我想从 2 个单独的类中输出数据,一个是基类,一个是派生类,我想重载
#include <iostream>
using namespace std;
class A
{
char* A;
char* B;
public:
A() {A = ' '; B = ' ';}
A(char* pLast, char* pFirst)
{
A = new char [strlen(pLast) + 1];
B = new char [strlen(pFirst) + 1];
strcpy(A,pLast);
strcpy(B,pFirst);
};
}
class C:public A
{
int X;
char Y;
int Z;
public:
C(char* A, char* B, int X, char Y, int Z)
:A(A,B)
{
//do stuff here
}
friend std::ostream& operator<<(std::ostream& out, const C& outPut)
{
out << outPut.A << "," << outPut.B << "," <<outPut.X<< "," << outPut.Y << "," << outPut.Z << endl;
return out;
}
};
当我尝试运行它时,它告诉我 A 和 B 超出范围,这是有道理的,因为这些成员在 A 类中是私有的,我不知道如何解决这个问题。我尝试创建 getter 方法来访问 A 和 B,但数据显示为空白。我什至尝试将 A 类的对象添加为 B 类的成员,以尝试允许访问 B 类中的成员,但数据仍然为空白。我该如何解决这个问题?
【问题讨论】:
-
你为什么要用你已经在课堂上使用过的名字来命名成员?
-
与问题没有直接关系,但就目前而言,
B是A的嵌套类(除了派生自A)。你想要这样吗? -
除了尼克说的,
A的构造函数也有问题。你根据成员A的当前大小分配空间,而不是根据pLast和pFirst的大小。
标签: c++ inheritance operator-overloading splice member-access