【问题标题】:Passing object from another class to a constructor of the other in C++?在 C++ 中将对象从另一个类传递给另一个类的构造函数?
【发布时间】:2019-03-09 10:18:35
【问题描述】:

我有 2 个类 - 在第二个类中,我想传递 CAdress 类的一个对象,并通过它的 explicit constrcutor,为 CStudent 类中的成员 ar 分配相应的值?我想问我该怎么做?提前致谢!

class CAdress {
    string street;
    string postal;
    string city;
public:
    CAdress() {
        street = "Studentska #1";
        postal = "9010";
        city = "Varna";
    };
    CAdress(string st, string pos, string ct) {
        street = st;
        postal = pos;
        city = ct;
    }
};



  class CStudent : public CPerson2 {
        string fn;
        CAdress adr;
    public:
        CStudent() {
            fn = "12131547";
        }
        CStudent(string nm, CAdress add, string egnn) {
            name = nm;
            //how to give values to the adress?
            //add = ?
            egn = egnn;

        }

    };

【问题讨论】:

标签: c++ oop object constructor


【解决方案1】:

您可以创建一个复制构造函数并直接复制该值。 https://www.geeksforgeeks.org/copy-constructor-in-cpp/。默认情况下,编译器提供一个,但它只做浅拷贝。所以有时最好创建一个。

    CStudent(string nm, CAdress add, string egnn) {
        name = nm;
        adr = add;
        egn = egnn;
    }

【讨论】:

  • "adr = new CAdress(add.street, add.postal, add.city);"这在 Java 中有效,但在 C++ 中无效
  • OP 的CAdress 不需要用户定义一个。
【解决方案2】:

这样做效率更高

CStudent (const string& nm, const CAdress& add, const string& egnn) :
     name (nm),
     adr (add),
     egn (egnn) {}

参考阅读https://en.cppreference.com/w/cpp/language/initializer_list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多