问题描述
我现在从Java迁移到C ++,每当Java中常用的概念不直接映射到C ++时,我遇到了一些困难。例如,在Java中我会做一些类似的事情:
I'm moving from Java to C++ right now and I'm having some difficulties whenever a commonly used concept in Java doesn't map directly into C++. For instance, in Java I would do something like:
Fruit GetFruit(String fruitName) {
Fruit fruit;
if(fruitName == "apple") fruit = new Fruit("apple");
else if(fruitName == "banana") fruit = new Fruit("banana");
else fruit = new Fruit("kumquat"); //'cause who really wants to eat a kumquat?
return fruit;
}
当然,在C ++中 / code>语句实际上创建一个水果。这是否意味着我必须有一个默认的构造函数?这似乎不安全!如果我的默认水果逃脱了怎么办?
Of course, in C++ the Fruit fruit;
statement actually creates a fruit. Does this mean I have to have a default constructor? This seems unsafe! What if my default fruit escaped?
推荐答案
C ++给你创造水果更令人头痛。根据您的需要,您可以选择以下选项之一:
C++ gives you much more headache when it comes to creating fruits. Depending on your needs, you can choose one of the following options:
1)在堆栈上创建一个水果并返回一个副本(你需要一个副本构造函数)然后和必须提供一些默认的水果,以防名称不匹配:
1) create a Fruit on a stack and return a copy (you need a copy constructor) then and must provide some default fruit in case the name does not match:
Fruit GetFruit(const std::string &name)
{
if ( name == "banana" ) return Fruit("banana");
if ( name == "apple" ) return Fruit("apple");
return Fruit("default");
}
2)在堆上创建一个Fruit并且小心,空指针返回,还记得删除这个水果在某个地方,并注意它是只删除一次,只有它的所有者(并注意没有一个指针指向删除的水果):
2) create a Fruit on a heap and take care, that there could be null-pointer returned and also remember to delete this fruit somewhere and take care that it is deleted only once and only by its owner (and take care that noone holds a pointer to the deleted fruit):
Fruit* GetFruit(const std::string &name)
{
if ( name == "banana" ) return new Fruit("banana");
if ( name == "apple" ) return new Fruit("apple");
return NULL;
}
3)最后,使用智能指针避免许多可能的指针问题但是处理空指针)。此选项最接近您的Java编程体验:
3) and finally, use a smart pointer to avoid many possible pointer problems (but take care of null pointers). This option is the closest to your Java programming experience:
typedef boost::shared_ptr<Fruit> FruitRef;
FruitRef GetFruit(const std::string &name)
{
if ( name == "banana" ) return new Fruit("banana");
if ( name == "apple" ) return new Fruit("apple");
return FruitRef();
}
这篇关于C ++:创建未初始化的占位符变量而不是默认对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!