定義構造對象:通過調用構造函數(方法)類的明確
#pragma once
#include <string>
#include <utility>
namespace impress_errors {
#define BUFSIZE 512
class Error {
public:
Error(int number);
Error(std::string message);
Error(const char *message);
bool IsSystemError();
std::string GetErrorDescription();
private:
std::pair <int, std::string> error;
char stringerror[BUFSIZE]; // Buffer for string describing error
bool syserror;
};
} // namespace impres_errors
我在文件posix_lib.cpp一些代碼片段:
int pos_close(int fd)
{
int ret;
if ((ret = close(fd)) < 0) {
char err_msg[4096];
int err_code = errno;
throw impress_errors::Error::Error(err_code); //Call constructor explicitly
}
return ret;
}
而在另一個文件fs_creation。 cpp:
int FSCreation::GenerateFS() {
int result;
try {
result = ImprDoMakeTree(); //This call pos_close inside.
}
catch (impress_errors::Error error) {
logger.LogERROR(error.GetErrorDescription());
return ID_FSCREATE_MAKE_TREE_ERROR;
}
catch (...) {
logger.LogERROR("Unexpected error in IMPRESSIONS MODULE");
return ID_FSCREATE_MAKE_TREE_ERROR;
}
if(result == EXIT_FAILURE) {
return ID_FSCREATE_MAKE_TREE_ERROR;
}
return ID_SUCCESS;
}
在我的編譯器的版本與一個被編譯和工作正確:
克++(Ubuntu的/ Linaro的4.4.4-14ubuntu5)4.4.5(Ubuntu的小牛 - 10.04)
在編譯器的另一個版本:
克++(Ubuntu的/ Linaro的4.5.2-8ubuntu4)4.5.2(Ubuntu的獨角鯨 - 11.04)它會導致
錯誤:
posix_lib.cpp:在函數 '詮釋pos_close(INT)':
posix_lib.cpp:363:46:錯誤:無法直接調用構造函數'impress_errors :: Error :: Error'
posix_lib.cpp:363:46:錯誤:對於函數樣式轉換,刪除多餘的':: Error'
問題:
1. 爲什麼這個工作在一個版本的g ++,並在另一個版本上失敗?
2. 當我顯式調用創建對象的構造函數時會發生什麼?這是對的嗎?
爲什麼這是行得通的?
@James Kanze:§3.4.3.1/ 2似乎另有說明。我在這裏沒有最終的標準,只有n3290,但我確信最終文件在這個部門沒有太大變化。這似乎意味着'impress_errors :: Error :: Error'不能用作類型名稱,儘管注入。 –
@n.m我正在看n3291,但我不明白它在這裏如何應用。 §3.4.3.1/ 2首先說「在構造函數是一個 可接受的查找結果[...]」的查找中,在這裏不是這種情況。 –
那裏的例子說'A :: A a; //錯誤,A :: A不是類型名稱,爲什麼?它可以是另一個位置的類型名稱嗎?我知道例子不是規範的,但是這裏的意圖是什麼? –