2011-09-06 95 views
1

說我有兩個班,在兩個不同的標題,叫做:類賦值運算符=的問題

class TestA 
{ 
    public: 
     int A; 
}; 

class TestB 
{ 
    public: 
     int B; 
}; 

,我想給他們倆一個賦值操作符給對方,所以它是這樣的:

class TestB; //Prototype of B is insufficient to avoid error with A's assignment 

class TestA 
{ 
    public: 
     int A; 
     const TestA &operator=(const TestB& Copy){A = Copy.B; return *this;} 
}; 

class TestB 
{ 
    public: 
     int B; 
     const TestB &operator=(const TestA& Copy){B = Copy.A; return *this;} 
}; 

如何做到上述同時避免調用/使用類TestB時尚未定義的明顯錯誤?

回答

6

您不能將文件中的函數定義寫入,因爲這需要循環依賴。

要解決這個問題,請先聲明這些類並將它們的實現放在一個單獨的文件中。

A的頭文件:

// A.h 

// forward declaration of B, you can now have 
// pointers or references to B in this header file 
class B; 

class A 
{ 
public: 
    A& operator=(const B& b); 
}; 

A的實現文件:

// A.cpp 
#include "A.h" 
#include "B.h" 

A& A::operator=(const B& b) 
{ 
    // implementation... 
    return *this; 
} 

遵循相同的基本結構B爲好。

+0

好的,謝謝。 – SSight3

+1

你甚至不需要單獨的文件,你只需要將類定義從成員函數定義中分離出來。 –

1

如果您將兩個頭文件都包含在.cpp文件中,它應該可以工作。確保頭文件中有兩個類的完整定義。

+0

我認爲這個問題是因爲operator =是內聯的而不是單獨的。謝謝你。 – SSight3