类的定义:
#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;
}
在我的编译器版本上,这个编译器可以正常工作:
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
似乎是尝试命名构造函数。构造函数没有名字;它们不是您可以随心所欲地找到和调用的函数(同样,不是按照您的意思)。
关于c++ - 通过显式调用构造函数(方法)构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7565776/