我有一個基類BaseOption
class BaseOption {
protected:
BaseOption(char short_name, std::string &name, std::string &description)
: short_name(short_name) {
this->name = &name;
this->description = &description;
}
~BaseOption() {
delete name;
delete description;
}
friend std::ostream &operator<<(std::ostream &out, const BaseOption &option) {
return out << "-" << option.short_name << "\t--" << option.name << "\t" << option.description;
}
char short_name;
std::string *name;
std::string *description;
};然后有個派生類DefaultOption:
class DefaultOption : public BaseOption {
public:
DefaultOption(char short_name, std::string &name, std::string &description)
: BaseOption(short_name, name, description) {}
};還有一個類Options:
class Options {
public:
Options() = default;
~Options() {
for (const auto &item : options) {
delete &item;
}
}
void Add(std::string name, std::string description) {
char short_name = 0;
std::string _name;
if (name.length() > 1) {
if (name[1] == '|') {
short_name = name[0];
_name = std::string(name, 2, name.length());
}
} else if (name.length() == 1) {
short_name = name[0];
}
DefaultOption option(short_name, _name, description, flag);
// TODO
}
friend std::ostream &operator<<(std::ostream &out, const Options &options) {
for (const auto &item : options.options) {
std::cout << item << std::endl;
}
return out;
}
private:
std::vector<BaseOption *> options;
};在類Options中的Add方法該怎么像options中添加元素呢,一直報無效指標。
uj5u.com熱心網友回復:
如果涉及到包含指標類,最好實作他的拷貝建構式,賦值函式,如果講究效率,還有移動建構式,以及移動賦值函式uj5u.com熱心網友回復:
另外作為基類,最好把解構式寫成virtual的uj5u.com熱心網友回復:
好的,等下我試試
uj5u.com熱心網友回復:
options.push_back(new BaseOption( ) );轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/230829.html
標籤:新手樂園
上一篇:函式傳參問題
