![](/img/trans.png)
[英]Having trouble passing an object into the constructor of another class in 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.