這似乎是一個微不足道的問題,但現在我掛了幾個小時(可能太多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