【问题标题】:How should i write needed constructor for class which includes dynamic array?我应该如何为包含动态数组的类编写所需的构造函数?
【发布时间】:2019-11-07 14:54:09
【问题描述】:

前辈! 我一直被困在这个话题上,找不到为 K1K2 类编写跟随构造函数(和方法)的方法:

  • 默认构造函数
  • 复制构造函数和重写方法。
  • 正确的重载运算符
    class K1 {
    string* p1; // p1 in future should be dynamic array
public:
    K1() : p1(new string) {}; // my version of def. constructor
    ~K1() { delete p1; }; // destructor
    K1(const K1& k) : p1(new string(*k.p1)) {}; // my version of copying constructor
    K1& operator= (const K1& copy) { // rewriting method in my vision
        *p1 = *copy.p1;
        return *this;
    }
}; 

class K2 {
    K1 p1;
    double p2;
public: 
    K2(const string & one, const string & two, const double & price) // mostly stucked here: how can i reforward data from here to K1`s pointer (which is an array)
};
int main() {
    K2 ob1, ob2; // testing code
    const K2* wsk1 = new K2("kawa", "z mlekiem", 4.50);
    const K2 ob3(*wsk1);
    delete wsk1;
    K2* wsk2 = new K2(ob3);
    ob2 = *wsk2;
    cout << ob3;
    return 0;
}

提前感谢您的帮助,伙计们!

【问题讨论】:

  • 还有什么问题?到目前为止什么不起作用?编译错误?运行时错误?有什么不想要的结果?陈述一个特定的问题。除此之外,如果你使用合适的容器,你的生活会更轻松,在你的情况下可能是std::vector&lt;std::string&gt; p1;。此外,new 的任何使用都可能发生错误(不是在您的代码中,而是在将来的某个时候,它会),尝试通过使用容器和智能指针来尽可能少地使用它(比如std::shared_ptr)。
  • 另外,尝试使用描述性名称。我们不知道 K1 和 K2 应该是什么以及您要达到的目标。如果他们有 Student 或 ComplexNumber 这样的名字,我们可以提供更好的建议。成员和变量也是如此。
  • "string* p1; // p1 in future should be dynamic array",所以 std::vector&lt;std::string&gt; 和 0 规则 :-)

标签: c++ class pointers


【解决方案1】:

为 K1 添加构造函数

K1(const string& s) : p1(new string(s)){};

然后在K2

K2(const string & one, const string & two, const double & price) : p1(one){}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2014-02-25
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多