2012-11-29 18 views
0

你好,我目前面臨的一個問題是,我想從2個獨立的類輸出數據,一個是基類,一個是派生類,我想超載運算符輸出<輸出在一次,但所有的數據似乎都無法做到的,我有這樣的事情:當數據拼接時輸出成員變量C++

#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類中的成員,但數據仍然是空白的。我如何解決這個問題?

+2

爲什麼你用已經在類中使用過的名稱命名成員? – imreal

+1

與問題沒有直接關係,但是現在看來,'B'是'A'的嵌套類(除了從'A'派生出來之外)。你想這樣嗎? – jogojapan

+2

除了Nick所說的外,'A'的構造函數還有一個問題。您根據成員「A」的當前大小分配空間,而不是根據「pLast」和「pFirst」的大小來分配空間。 – jogojapan

回答

2

有幾種處理方法。顯然,一種方法是使A的成員受到保護而不是私有。派生類B可以訪問它們。

另一種方法確實是getter函數。他們沒有爲你工作的事實與你的構造函數中的問題以及代碼中的其他問題有關。但是公共獲得者也有缺點,即讓任何人(不僅僅是派生類)能夠訪問數據成員的值。

這是第三個辦法,我認爲是有道理的,你的情況:在A定義一個單獨的operator<<,並使用該運營商的,當你定義一個B

#include <cstring> 
#include <iostream> 

using namespace std; 

class A 
{ 
    char* _a; 
    char* _b; 
public: 
    A() 
    : _a(),_b() 
    { } 

    A(const char *pLast, const char *pFirst) 
    : _a(new char [std::strlen(pLast)]), 
     _b(new char [std::strlen(pFirst)]) 
    { 
    strcpy(_a,pLast); 
    strcpy(_b,pFirst); 
    } 

    friend std::ostream& operator<<(std::ostream& out, const A& obj) 
    { 
    out << obj._a << "," << obj._b; 
    return out; 
    } 
}; 

class B : public A 
{ 
    int _x; 
    char _y; 
    int _z; 

public: 
    B(const char *pLast, const char *pFirst, int x, char y, int z) 
    : A(pLast,pFirst), 
     _x(x),_y(y),_z(z) 
    { } 

    friend std::ostream& operator<<(std::ostream& out, const B& obj) 
    { 
    out << static_cast<const A&>(obj) << ',' 
     << obj._x << ',' 
     << obj._y << ',' 
     << obj._z; 
    return out; 
    } 
}; 

int main() 
{ 
    B b("hello","world",1,'a',3); 
    std::cout << b << std::endl; 
    return 0; 
} 

我已經也糾正了我發現的其他問題,所以上述實際工作。