如何使用抽象类作为每个循环的索引变量的类型?
我正在将我的 Java 程序翻译成 c ++ 。我遇到了一个问题,试图使用多态性与 java 中的方式相同。
我的代码看起来像这样:
class Base
{
public:
virtual void print() = 0;
};
class Derived_1 : public Base
{
public:
void print()
{
std::cout << "1" << std::endl;
}
};
class Derived_2 : public Base
{
public:
void print()
{
std::cout << "2" << std::endl;
}
};
下一个是我尝试过的主要方法的两个版本,都给我编译器错误:
1:
int main(int argc, char const *argv[])
{
std::vector<Base> v;
v.push_back(Derived_1());
v.push_back(Derived_2());
for(Base i: v)
{
i.print();
}
return 0;
}
错误:
object of abstract class type "Base" is not allowed:C/C++(322)
main.cpp(35, 14): function "Base::print" is a pure virtual function
2:
int main(int argc, char const *argv[])
{
std::vector<Base*> v;
v.push_back(new Derived_1());
v.push_back(new Derived_2());
for(Base* i: v)
{
i.print();
}
return 0;
}
错误:
expression must have class type but it has type "Base *"C/C++(153)
你们将如何解决这个问题?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 java to c ++ ,有很多值得照顾的;特别是内存管理!
在第一个显示的情况下,您将对象切片。请参阅什么是对象切片?
为了访问虚拟函数,您应该使用过
std :: vector&lt; base*&gt;
(即指针的向量base
)或std :: vector&lt; std :: simolor_ptr&lt; base代码>或
std :: vector&lt; std :: shared_ptr&lt; base&gt;&gt;
(即智能指针的向量base
)。在您的第二个代码中,您的
v
是指向base
指针的向量,这意味着您需要通过- &gt;
操作员访问成员。即,您应该已经访问了
print()
如下:或者:
另请注意:
在您的第二种情况下,无论您
new
ed n ew ed都必须是>删除
d,以使程序不会泄漏内存。另外,我们有智能内存管理base base
缺少Virtual
destructor,当delete
ing ovjects时,它将导致不确定的行为。您应该为定义的行为添加一个。请参阅:何时使用虚拟破坏者?使用
std :: simolor_ptr ,您的代码看起来像(示例代码):
Coming from java to c++, there are a lot to take-care; Especially memory management!
In your first shown case, you are slicing the objects. See What is object slicing?
In order to access the virtual functions, you should have used
std::vector<Base*>
(i.e. vector of pointer toBase
), orstd::vector<std::unique_ptr<Base>>
orstd::vector<std::shared_ptr<Base>>
(i.e. vector of smart pointer toBase
).In your second shown code, your
v
is a vector of pointer toBase
, meaning you need to access the members via the->
operator.i.e. You should have accessed the
print()
as follows:Or alternatively:
Also note that:
In your second case, whatever you
new
ed must bedelete
d, so that the program doesn't leak memory. Alternately, we have smart memory managementThe
Base
is missing avirtual
destructor, which will lead to undefined behavior whendelete
ing the ovjects. You should add one for defined behavior. See: When to use virtual destructors?Using
std::unique_ptr
, your code will look like (example code):