lik*_*ern 2 c++ constructor object
课程定义:
#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
Run Code Online (Sandbox Code Playgroud)
我在文件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;
}
Run Code Online (Sandbox Code Playgroud)
在另一个文件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;
}
Run Code Online (Sandbox Code Playgroud)
在我的编译器版本中,这个编译并且工作正确:
g ++(Ubuntu/Linaro 4.4.4-14ubuntu5)4.4.5(Ubuntu Maverick - 10.04)
在另一个版本的编译器上:
g ++(Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2(Ubuntu Narwhal - 11.04)它导致
错误:
posix_lib.cpp:在函数'int pos_close(int)'中:
posix_lib.cpp:363:46:错误:无法直接调用构造函数'impress_errors :: Error :: Error'
posix_lib.cpp:363:46:错误:对于函数式转换,删除冗余的":: Error"
问题:
1.为什么这个工作在一个版本的g ++上,而在另一个版本上失败?
2. 当我显式调用构造函数来创建对象时会发生什么?这是对的吗?
为什么这个有效?
你没有调用构造函数(嗯,你是,但不是你的意思).语法ClassName(constructor params)意味着ClassName使用给定参数为其构造函数创建该类型的临时对象.所以你不是简单地调用构造函数; 你正在创建一个对象.
所以你正在创建一个Error对象.你的问题是名称Error是impress_errors::Error,而不是"impress_errors :: Error :: Error".第二个::Error似乎是尝试命名构造函数.构造者没有名字; 它们不是你能找到的功能,而是随心所欲地打电话(再次,不是你的意思).