簡體   English   中英

將對象從另一個類傳遞給 C++ 中另一個類的構造函數?

[英]Passing object from another class to a constructor of the other in C++?

我有2個類-在第二個我想通過類的對象CAdress其,並通過explicit constrcutor ,分配構件ar從類CStudent相應值? 我想問一下我該怎么做? 提前致謝!

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;

        }

    };

這樣做效率更高

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

您可以創建一個復制構造函數並直接復制值。 https://www.geeksforgeeks.org/copy-constructor-in-cpp/ 默認情況下,編譯器提供一個,但它只執行淺拷貝。 所以最好有時創建一個。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM