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);
。我在那裏調用一個構造函數,它爲什麼被當作一個類型轉換?
我知道這不是你的問題的答案,但你爲什麼不使用矢量?您可以在兩個方向上迭代它,可能不需要反轉緩衝區。如果不是,則可以使用STL完成對緩衝區的反轉:https://stackoverflow.com/questions/8877448/how-do-i-reverse-a-c-vector – Jens
帶有兩個下劃線'__'的名稱由標準保留。 – Jens
@PeterT:Buffer.h包含'cerror'。與errno.h不一樣嗎? @Jens:我是C++的新手。所以你看我把C和C++混合在一起。 –