2011-11-24 93 views
0

这是从属类头C++构造继承工作不正常

#ifndef TransHeader 
#define TransHeader 
#include <string> 
#include "CipherHeader.h" 

using namespace std; 
class Trans : public Cipher { 
    public: 
    Trans(string filenameIn); 
    const static int MAXSIZE = 10000; 
    void createArray(); 
    void transEncrypt(); 
    void transDecrypt(); 


    private: 
     //string Key; 
     //string inputData; 
     char dataArray[MAXSIZE][MAXSIZE]; 


}; 

#endif 

这是继承报头

#ifndef CipherHeader 
#define CipherHeader 
#include <string> 
using namespace std; 

class Cipher { 
    public: 
     const static int MAXSIZE = 10000; 
     Cipher(string filenameIn); 
     void getKey(); 
     void flagHandle(string); 
     string Key; 
     string inputData; 
     string filename; 
     string flags; 

     string readFile(); 
     void writeFile(); 
    private: 




}; 

#endif 

问题是后我调用基构造

Trans::Trans(string filenameIn) : Cipher(filenameIn) {} 

我不能像这样在普通文件中调用构造函数:

#include "Trans.cpp" 

int main() { 
string a = "asdf"; 
Trans *c = new Trans(a); 

} 

这导致了这个错误:

g++ test.cpp -o test.out 
/tmp/ccbuqMYr.o: In function `Trans::Trans(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)': 
test.cpp:(.text+0x35): undefined reference to `Cipher::Cipher(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' 
/tmp/ccbuqMYr.o: In function `Trans::Trans(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)': 
test.cpp:(.text+0xa5): undefined reference to `Cipher::Cipher(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' 
collect2: ld returned 1 exit status 

用密码代替反式工作得很好,并运行。我尝试了我所知道的一切,过度搜索,无法弄清楚这个错误。其他设计问题等将在稍后处理,这是我的主要问题。请帮忙。

编辑::密码

Cipher::Cipher(string filenameIn) { 

filename = filenameIn; 

readFile(); 
getKey(); 

} 
的定义
+4

这是一个链接错误。你要么错过了'Cipher :: Cipher()'或者定义所在的'.cpp'文件的定义。 – iammilind

+0

响应很迟,但如果我没记错的话,这个人解决了我的问题。 –

回答

1

你需要构建的所有源文件:

g++ test.cpp trans.cpp cipher.cpp -o test 

这会给你一个新的错误,因为你包括test.cpptrans.cpp源文件,而比头文件 - 修复,并应该建立没有进一步的问题。

+0

这工作,现在我只是处理分段错误,这是我怀疑的另一个问题!谢谢! –

+0

用测试文件中的密码代替Trans,运行时没有分段错误...如果您有任何想法,为什么,我将不胜感激 –

+0

修复了您的帮助,非常感谢 –

3

确定规则1 - 永远不把“使用”的语句在一个头文件! ;-)

好的,你需要调用基类的构造函数。

所以:

Trans::Trans(const std::string &f) // notice pass by reference 
    :Cipher(f) 
{ 
} 
+0

对不起,我不知道如何解决这个问题。我试图从用户使用cin检索字符串,但没有奏效。 –

+0

进行更改后,我得到了同样的错误 –

+0

尝试的#include 的#include Base类 { 市民: 基地(常量的std :: string&F) :m_name(F) {} private: std :: string m_name; }; 类DERIV:公共基地 { 公共: DERIV(常量的std :: string&F) :基础(F) { } }; int main(int argc,char * argv []) { Deriv f(“foobar”); return 0; } –