【发布时间】:2009-06-30 15:13:31
【问题描述】:
这似乎是一个微不足道的问题,但我已经坚持了几个小时(也许太多的 Java 杀死了我的 C++ 脑细胞)。
我创建了一个具有以下构造函数的类(即没有默认构造函数)
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++ 中的代码看起来相似不是真正的等效代码。
标签: c++ exception constructor