我应该如何为包含动态数组的类编写所需的构造函数?

问题描述 投票:0回答:1

前辈!我一直被这个话题困扰,无法找到为<< K1和K2

两个类编写跟随构造函数(和方法)的方法。
    默认构造函数
  • 复制构造函数和重写方法。
  • 正确的重载运算符<
  • 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;
}
谢谢您的帮助,伙计们!

前辈!我一直停留在这个话题上,找不到为K1和K2类编写跟随构造函数(和方法)的方法:默认构造函数复制构造函数和重写方法。 ...

c++ class pointers
1个回答
0
投票
为K1添加构造函数
© www.soinside.com 2019 - 2024. All rights reserved.