類物件作為函式引數
阿新 • • 發佈:2019-01-10
網上看見一段程式碼,是關於類物件作為函式的引數,其中有幾點知識,貼出來大家一起學習。
直接來看程式碼:
1.首先要明確void display(people x){...}是傳值方式傳參,實參要向形參複製物件,在複製物件時會呼叫拷貝建構函式;#include <iostream> #include <string> using namespace std; class people { private: char *name; int age; public: people(char *namestr,int i); ~people(); char *getname(); int getage(); }; people::people(char *namestr,int i) { name=new char[strlen(namestr)+1]; strcpy(name,namestr); age=i; } people::~people() { delete name; } char *people::getname() { return name; } int people::getage() { return age; } void display(people x) { cout<<"people\'s name: "<<x.getname()<<endl; cout<<"people\'s age: "<<x.getage()<<endl; } int main() { people p("xieyi",30); display(p); return 0; }
2.由於people類中沒有顯示定義拷貝建構函式,將使用預設拷貝建構函式,那麼將不會自動複製堆資源(即通過new得到的資源);
3.因此,void display(people x){...}執行時,會呼叫預設拷貝建構函式,所以x物件中的name屬性沒有賦值,指向了未知的地址,因此x.getname()會出錯;
解決的辦法有兩個:
1.使用引用傳參
void display(people& x) void display(const people& x);
2.顯示定義拷貝建構函式
people(const people& x)
{
this->name = x.name;
this->age = x.age;
}