簡體   English   中英

在另一個類構造函數中初始化類對象

[英]Initializing class object inside the other class constructor

我有一個班級,它的名字叫A,而一個班級有3個私人班級。

class A{
    public:
          A();
          A(int num);
          A(C& mC, P& mP, M& mM, int num);
    //there is a getter and setter for all member this only one example(please check are they right?)
          M getM()const{return pM;} 
          void setM(M classM){ pM = classM ;}
        private:
            C& pC;
            P& pP;
            M& pM;
            int digit= 0;
        };

我在參數結構中這樣做:

A::A(C& mC, P& mP, M& mM, int num):pC(mc),pP(mP),pM(mM)
{
// doing someting here
}

但是,當我寫一些對我說的編譯器時,我無法為默認和第一個參數構造編寫代碼:

錯誤:“類A&”中未初始化的引用成員[-fpermissive] A :: A(){

注意:“ A&A :: pP”應初始化為A&pP;

這樣的東西,一些錯誤和注釋。

我該怎么辦? 如何在默認和第一個參數構造中初始化類?

A包含對其他對象的引用 與指針不同,引用不能為空。 要使其工作,您要么需要:

  • 使用指針代替引用,並將其初始化為nullptr ,因為構造函數中未提供有效的對象
  • 按值存儲這些成員。 這涉及原始參數的副本,並且語義不同-可能不是您所需要的。

暫無
暫無

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

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