的對象我做了這個類構造使得指針類型
class Person {
public:
Person(const std::string& name, const std::string& email, const std::string& city)
: name(name), email(email), city(city) {
}
bool hasCity() const {
return city.compare("") == 0;
}
void print() const {
std::cout << name + " <" + email + ">";
if(hasCity()){
std::cout << ", " + city;
}
std::cout << std::endl;
}
bool equalTo(const Person& comparedPerson) const {
return email.compare(comparedPerson.email) != 0;
}
bool equalId(std::string comparedId){
return email.compare(comparedId) != 0;
}
const std::string name;
const std::string email;
const std::string city;
};
什麼是我的問題是,當我嘗試與創建新的聯繫人:
const Person& newPerson = (const Person &) new Person(name, email, city);
我得到這個錯誤
error: invalid cast of an rvalue expression of type 'Person*' to type 'const Person&'
const Person& newPerson = (const Person &) new Person(name, email, city);
我想爲什麼新創建的Person是Person而不是Person。
看看智能指針:'std :: unique_ptr'和'std :: shared_ptr'。這是一個更好的實踐來操作分配的內存 – Garf365
只需做'const Person&newPerson = Person(name,email,city);' –
您還應該重載插入操作符('<<')來代替'print'方法。 – erip