2016-11-14 114 views
0

我有一個自定義異常類:力調用構造,而不是泛函樣式轉換

Exception.cc:

#include "Exception.h" 


const char* Exception::getMessage() 
{ 
    return strerror(this -> error_code); 
} 

int Exception::getErrno() 
{ 
    return this -> error_code; 
} 

Exception::Exception(int errno) 
{ 
    this -> error_code = errno; 
} 

Exception.hh

#ifndef __EXECPTION_H__ 
#define __EXECPTION_H__ 

#include <string.h> 

class Exception 
{ 
private: 
    int error_code; 

public: 

    const char* getMessage(); 

    int getErrno(); 

    Exception(int errno); 
}; 

#endif 

而另一家定製類緩衝區它提供了逐字節地反轉緩衝區內容的功能:

Buf fer.h:

#ifndef __BUFFER_H__ 
#define __BUFFER_H__ 

#include <stdlib.h> 
#include <cerrno> 

class Buffer 
{ 

private: 
    char * buffer; 
    int size; 


public: 
    Buffer(int size); 
    ~Buffer(); 
    void reverse(); 

    friend class File; 
}; 

#endif 

Buffer.cc:

#include "Buffer.h" 
#include "Exception.h" 


Buffer::Buffer(int size) 
{ 
    this -> size = size; 
    this -> buffer = (char *)malloc(size); 
    if(this -> buffer == NULL) 
    throw Exception(errno); 
} 

Buffer::~Buffer() 
{ 
    if(this -> buffer == NULL) 
    free(this -> buffer); 
} 

void Buffer::reverse() 
{ 
    char tmp; 
    int i; 
    char * tmpb = this -> buffer; 
    for(i = 0; i < this -> size/2; i++) 
    { 
    tmp = (char)tmpb[i]; 
    tmpb[i] = tmpb[size - i - 1]; 
    tmpb[size - i - 1] = tmp; 
    } 
} 

main.cc

#include "Buffer.h" 
#include "Exception.h" 
#include <stdlib.h> 

#include <iostream> 
using namespace std; 

int main (const int argc, const char** argv) 
{ 
    if(argc != 3) 
    exit(-1); 


    return 0; 
} 

編譯器給我回的錯誤:

Buffer.cc:10:11: error: no matching conversion for functional-style cast from 'int' to 'Exception' 
    throw Exception(errno); 
      ^~~~~~~~~~~~~~~ 
./Exception.h:6:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'int' to 'const Exception' for 1st 
     argument 
class Exception 
    ^
./Exception.h:17:3: note: candidate constructor not viable: no known conversion from 'int' to 'int (*(*)())' for 1st argument 
    Exception(int errno); 
^
1 error generated. 

它看起來像編譯器誤解throw Exception(errno);。我在那裏調用一個構造函數,它爲什麼被當作一個類型轉換?

+0

我知道這不是你的問題的答案,但你爲什麼不使用矢量?您可以在兩個方向上迭代它,可能不需要反轉緩衝區。如果不是,則可以使用STL完成對緩衝區的反轉:https://stackoverflow.com/questions/8877448/how-do-i-reverse-a-c-vector – Jens

+0

帶有兩個下劃線'__'的名稱由標準保留。 – Jens

+0

@PeterT:Buffer.h包含'cerror'。與errno.h不一樣嗎? @Jens:我是C++的新手。所以你看我把C和C++混合在一起。 –

回答

6

沒有「調用構造函數」這樣的事情。 Exception(errno)(Exception)errnostatic_cast<Exception>(errno)在您的代碼中都是相同的。

話雖這麼說,你的問題的根源是別的東西:你正在使用的保留名稱errno,這是一個標準的宏(以實現定義的內容)。宏對C++範圍沒有考慮,所以你的構造函數聲明實際上

Exception(int whatever_errno_actually_expands_to); 

是在我的gcc,這其實是:

Exception(int (*__errno_location())); 

解決辦法:不要標識符使用保留名稱。

相關問題