这似乎是一个微不足道的问题,但现在我挂了几个小时(可能太多Java杀死了我的C++ braincells)。用异常抛出构造函数初始化对象的正确方法
我创建了具有以下构造函数的类(即没有默认构造函数)
VACaptureSource::VACaptureSource(std::string inputType, std::string inputLocation) {
if(type == "" || location == "") {
throw std::invalid_argument("Empty type or location in VACaptureSource()");
}
type = inputType;
location = inputLocation;
// Open the given media source using the appropriate OpenCV function.
if(type.compare("image")) {
frame = cvLoadImage(location.c_str());
if(!frame) {
throw std::runtime_error("error opening file");
}
}
else {
throw std::invalid_argument("Unknown input type in VACaptureSource()");
}
}
当我想创建一个实例,我用
// Create input data object
try {
VACaptureSource input = VACaptureSource("image", "/home/cuneyt/workspace/testmedia/face_images/jhumpa_1.jpg");
}
catch(invalid_argument& ia) {
cerr << "FD Error: " << ia.what() << endl;
usage(argv[0]);
}
catch(runtime_error& re) {
cerr << "FD Error: " << re.what() << endl;
usage(argv[0]);
}
然而,在这种情况下,实例是本地块,我不能在其他地方引用它。另一方面,我不能说
VACAptureSource input;
在程序的开始,因为没有默认的构造函数。
这样做的正确方法是什么?
谢谢!
你会如何在Java中解决这个问题?应用相同的解决方案。这个问题不依赖于语言。不同的语言只为不同的语法提供了不同的语法来实现等效目的,考虑到当你在Java中定义一个变量时,你不是声明一个对象,而是一个_reference_(C++术语中的指针),所以在Java和C++中看起来类似的代码并不是真正等效的代码。 – 2009-06-30 22:15:23