2014-02-07 161 views
0

我做了一個父類和一個繼承類。主要是當我給繼承類的對象時會出現一個錯誤,例如「對象不可訪問」。這裏是我的代碼C++幫助類繼承

#include <iostream> 
#include <string> 
using namespace std; 

class Parents{ 
protected: 
    int age; 
    string name; 
public: 
    void getInfo(int hAge, string hName) 
    { 
     name = hName; 
     age = hAge; 
     cout << "Their son name is " << name << endl; 
     cout << "He is " << age << " years old" << endl; 
     cout << "His hair is red" << endl; 
     cout << "He is a boy" << endl; 
    } 
}; 

class Son : public Parents{ 
    Son(){ 
     name = "John"; 
     age = 25; 
    } 
}; 



int main(){ 
    Son boy; //object not accessible 

    system("pause"); 
    return 0; 
} 
+1

你需要構造公共 –

+0

還存在另一個問題。當我打電話給boy.getInfo()時,它表示調用的函數太少。爲什麼 – user3264250

+0

顯示你怎麼做 –

回答

2

Son類的構造函數在默認情況下是私有的。

class Son : public Parents{ 
public: 
    Son(){ 
     name = "John"; 
     age = 25; 
    } 
}; 

更新:

class Parents{ 
protected: 
    int age; 
    string name; 
public: 
    // Call this when you have not already assigned value to age and name 
    void getInfo(int hAge, string hName) 
    { 
     name = hName; 
     age = hAge; 
     cout << "Their son name is " << name << endl; 
     cout << "He is " << age << " years old" << endl; 
     cout << "His hair is red" << endl; 
     cout << "He is a boy" << endl; 
    } 

    // Call this when age and name already have values. 
    void getInfo() 
    { 
     cout << "Their son name is " << name << endl; 
     cout << "He is " << age << " years old" << endl; 
     cout << "His hair is red" << endl; 
     cout << "He is a boy" << endl; 
    } 
}; 

class Son : public Parents{ 
public: 
    Son(){ 
     name = "John"; 
     age = 25; 
    } 
}; 



int main(){ 
    Son boy; 
    boy.getInfo(); // Will call 2nd method 
    boy.getInfo(13,"First method"); // will call 1st method 
    system("pause"); 
    return 0; 
} 
+0

謝謝,還有另外一個問題。當我打電話給boy.getInfo()時,它表示調用的函數太少。爲什麼那個@Nishant Kumar – user3264250

+0

我沒有分配值 – user3264250

+0

你的函數'void getInfo(int hAge,string hName)'需要兩個值。因此,當您調用沒有參數的boy.getInfo()時,它與方法簽名不匹配。或者更改方法簽名或者嘗試重載方法 –

1

Son類的默認構造函數是私有的。因此,類Son的對象不能從類外部默認構建,就像您在main函數中嘗試使用Son boy;一樣。公開構造函數。

0

類內的成員是私有默認情況下可以訪問。 所以,如果你想定義自己的構造函數和您要訪問它,你應該指定它是公共