构造函数,成员对象

时间:2017-02-27 21:35:29

标签: c++ class

class Person{

public:
   Person(const string &nm, const string &surnm)
   : name(nm), surname(surnm)
   {

      cout << "\ntimes";
   }

private:
   string name;
   string surname;

};

class Family{

public:

  Family(Person &dad, Person &mom, Person &chld )
  : father(dad), mother(mom), child(chld)
  {
  }

private:

   Person father;
   Person mother;
   Person child;

};


int main(void){

  Person father1("John", "Gun");
  Person mother1("Marry", "Gun");
  Person child1("Alex", "Gun");

  Family firstFamily(father, mother, child);


  return 0;

}

编译此代码时,不会发生错误。但是,当我定义&#34; firstFamily&#34;对象,分配成员对象fathermotherchild的内存。如果为这些对象分配了内存,那么类Person的构造函数必须执行三次,并且我在main方法中使用类Person定义了三个对象。因此,Person类的构造函数必须执行6次。但是,它执行了三次。为什么它是三次?(可以理由是我在构造函数类Family中初始化了父母和子成员对象?并且没有为成员对象执行构造函数。)

1 个答案:

答案 0 :(得分:2)

  

因此,Person类的构造函数必须执行6次。但是,它   执行三次。

实际上,有6次调用Person的构造函数! 前三次是你自己创建的构造函数。

另外三次是编译器创建的默认复制构造函数。这将是Family的成员变量由Family构造函数的参数初始化。

我们可以通过覆盖Person的默认复制构造函数来证明这一点:

import Foundation
import Alamofire

// Retry a request every x seconds
class AutoRetrier: RequestRetrier{

    //MARK: Properties
    private var maxRetries: Int
    private var timeInterval: TimeInterval

    init(times maxRetries:Int, interval:TimeInterval){
        self.maxRetries = maxRetries
        self.timeInterval = interval
    }

    //MARK: RequestRetrier

    func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {

        // We're basically ignoring what type of error it is, and just retrying a number of times
        if request.retryCount <= UInt(maxRetries){
            completion(true, timeInterval)
        } else{
            completion(false, 0.0)
        }
    }
}

演示:http://coliru.stacked-crooked.com/a/7212d4918a61ceb9

我还对Family的构造函数进行了更改,以通过const引用获取其参数。这里不需要非const引用。

相关问题