簡體   English   中英

如何從另一個 class 訪問私有成員變量,其成員變量是第一個 class 的實例?

[英]How do I access to private member variable from another class whose member variable is instance of first class?

首先,感謝您的幫助。 我一直在學習C,最近才開始學習C++。

我試圖找出新的面向對象的概念。

例如,

class Contact{
    private:
        char name[30];
        char birthday[10];
        char email[30];
        char phone[20];
   public:
        char* getname();
        char* getbirthday();
        char* getemail();
        char* getphone();
        void setname(char* x);
        void setbirthday(char* y);
        void setemail(char* z);
        void setphone(char* w);
};
class ContactArray
{

    private:
    friend class contactArray;
        int max_size;
        Contact **contact1;
    public:
        friend class contactArray;
        ContactArray(int num)
        {
            int i;
            max_size = num;
            contact1 = new Contact*[max_size];
            
            for(i = 0; i <max_size ;i++)
            {
            contact1[i] = new Contact();
            }
            
        }
};

這是我現在正在使用的類,但如果我嘗試訪問“char name[30]”,我的程序將在使用“getname()”function 的地方停止。 所以更簡單地說,

ContactArray *contactArray;
contactArray = new ContactArray(6);

如果我像這樣創建實例,那么如果我創建名為 read_data 的 ContactArray 的公共方法,

void ContactArray::read_data(char* filename)
{
.........
....

fgets(str, BUFSIZE,fp);
ptr = strtok(str,";")
contact1[i]->setname(ptr);

printf("%s", contact1[i]->getname());//program stops here-----> here

}

如果我嘗試通過 getname() 檢查“setname(ptr)”是否正常工作,它會停止,所以我無法檢查。 其他的東西,如讀取文件或標記化工作正常,因為我可以使用基於 C 的 function 檢查我的道歉,我仍在學習 C++,但請忽略它們。

我認為這與 memory 分配有關,但不太清楚為什么。 幫我


    char* Contact::getname()
{
           char* n;
            strcpy(n,name);
            
            return n;
}

這是吸氣劑 function

Contact::getname() function 中的“n”指針在傳遞給 strcpy() 時未初始化。 這意味着 strcpy() 將嘗試將字符串復制到執行時恰好位於“n”指針中的任何 memory 地址(該地址可以是任何值,因為變量未初始化,並且很可能會導致崩潰)。 您應該使用n = new char[30]; 在 strcpy() 之前。

更好的是,您應該使用strncpy() function 代替,否則如果“名稱”字符串不是以空值結尾的(這也可能在這里發生),您的程序將執行緩沖區溢出。

Since you mentionned you're learning C++ comming from C, I'd suggest you look into the std::string class, which handles pretty much all the memory management hassle for you.

暫無
暫無

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

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