C ++继承:调用父类构造函数

时间:2015-12-08 19:23:29

标签: c++ class inheritance

我试图记住如何处理遗产而撞墙。假设我们有一个名为Fruits的父/基类和名为Apples的子/派生类。苹果只与水果有所不同,因为它有一个额外的变量,称为数字。我们如何实现它,以便默认情况下Apples始终使用值" Apples"来调用父类构造函数。 (名称)和SNACK(类型)?

水果将如此实施(

Fruits::Fruits(string name, KIND type): myName(name), myKind(type)
{}

如何实施苹果,以便如果苹果被称为苹果(),它默认名称为"苹果"并键入SNACK,数字为5? 这是对的吗?

Apples::Apples() : Fruits("Apple", SNACK)
{
    number = 5;
}
 Apples::Apples(int num)  : FoodItem("Pancakes", BREAKFAST )
{

}

2 个答案:

答案 0 :(得分:1)

This way is correct:

  Note: $email2 is array emails.
    require 'smtp/PHPMailerAutoload.php';
    $mail = new PHPMailer;
    //$mail->SMTPDebug = 2;                               // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "localhost";  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'contacto@xxx.com';                 // SMTP username
    $mail->Password = 'password';                           // SMTP password
    $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
    $mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
    $mail->Port = 465;                                    // TCP port to connect to
    $mail->CharSet = 'UTF-8';
    $mail->setFrom('contacto@xxx.com', 'Website');
    $mail->Subject = 'Se ha actualizado tu serie favorita';
    $mail->AltBody = 'Para ver este mensaje, use un visor de email compatible con HTML!';
    $mail->addReplyTo('contacto@xxx.com');
    $mail->isHTML(true);
    $mail->Body = 'The Body is HTML Code';
    if($vtitle == "Existe") {
    foreach($email2 as $email3)
    {
    $mail2 = clone $mail;
    $mail2->addAddress(''.$email3.'');     // Add a recipient
    $envio = $mail2->send();
    }
    } else {
        echo "El Capitulo no Existe";   
    }
    if(!$envio) {
        echo 'El Mensaje no ha podido enviarse.';
        echo 'Error: ' . $mail2->ErrorInfo;
    } else {
        echo 'El Mensaje ha sido enviado.';
    }

but this way would be better as it more readable and consistent:

Apples::Apples() : Fruits("Apple", BREAKFAST)
{
    number = 5;
}

答案 1 :(得分:0)

我会尝试这些:

// Default value for number
Apples::Apples() : Fruits("Apple", SNACK), number(5)
{
}

// Caller specified value for number
Apples::Apples(int num)  : FoodItem("Pancakes", BREAKFAST), number(num)
{
}