Mar*_*lka 0 c++ oop initialization
我什至不确定这是否可能,所以我想澄清一下。我有一个带有 const 字符串数组的父类,我希望它由其子类初始化,例如:
\n\nclass CParent{\n CParent();\n const char** strings;\n};\nRun Code Online (Sandbox Code Playgroud)\n\n和儿童班
\n\nclass CChild:CParent{\n CChild();\n};\n\nCChild::CChild()\n: CParent::strings{\n "First",\n "Second"\n}\n{\n CParent();\n // some code\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我需要这个,因为我将调用 CParent 的构造函数,并且我需要使用字符串。可以通过参数传递来完成,但我想知道这样的事情是否可能。
\n\n编辑:我在这里重写代码时忘记写一些东西,所以我宁愿复制粘贴它,这样我现在就不会忘记任何东西。我在 Andy Prowl 的帮助下使用字符串和向量重写了它:
\n\nclass CMenu {\npublic:\n CMenu(std::vector<std::string> const& s);\nprotected:\n std::vector<std::string> choicesStr;\n};\n\nCMenu::CMenu(std::vector<std::string> const & s) : choicesStr(s) {\n // code code\n}\n\nclass CGameTypeMenu : public CMenu {\npublic:\n CGameTypeMenu();\n};\n\nCGameTypeMenu::CGameTypeMenu() \n :CMenu(std::vector<std::string>("aaa","bbb")){ // This is where I \n get some nasty errors\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n错误看起来像这样:
\n\nIn file included from /usr/include/c++/4.7/vector:63:0,\n from CMenu.h:13,\n from CGameTypeMenu.h:11,\n from CGameTypeMenu.cpp:8:\n/usr/include/c++/4.7/bits/stl_uninitialized.h:77:3: required from \xe2\x80\x98static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const char*; _ForwardIterator = std::basic_string<char>*; bool _TrivialValueTypes = false]\xe2\x80\x99\n(5+ more similar lines follow)\nRun Code Online (Sandbox Code Playgroud)\n
只需以正确的方式进行即可(此解决方案仅适用于 C++11):
#include <vector>
#include <string>
class CParent
{
protected:
// ^^^^^^^^^^ Make sure your constructor is at least protected,
// or it will be inaccessible to derived classes
CParent(std::vector<std::string> const& s) : strings(s) { };
std::vector<std::string> strings;
// ^^^^^^^^^^^^^^^^^^^^^^^^ Use containers and classes from the C++ Standard
// Library rather than raw pointers
};
class CChild : public CParent
// ^^^^^^^^^^^^^^^^ I suppose you forgot this.
// Inheritance is private by
// default, which does not seem
// to be what you want
{
CChild();
};
CChild::CChild()
:
CParent({"First", "Second"}) // C++11 ONLY!
// ^^^^^^^^^^^^^^^^^^^
// Implicit construction of the vector of string
{
// some code
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2242 次 |
| 最近记录: |