繁体   English   中英

使用私有派生类的构造函数初始化基类的数据成员

[英]Initializing data members of base class using the constructor of privately derived class

我是C ++编程的新手,我正在尝试执行以下代码,但显示错误

没有用于调用“ Flower :: Flower()”的匹配函数Rose(字符串n =“无花”,字符串c =“红色”):color(c){}

即使我在类Flower中给了参数构造函数,它仍然说没有匹配的函数调用。

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


class Flower
{

public:
string name;


Flower (string n):name (n)
  {
  }


void getFlowerName ()
  {
    cout << name << " " << "is" << " ";
} 

};


class Rose:private Flower
{               // Inherit Flower as private
public:
string color;


    /* Initialize name and color data members */ 
Rose (string n = "No flower", string c = "Red"):color (c)
  {
  } 

void getFlowerName (Rose & r)
  {
    cout << r.color << endl;
  } 

    //  using Flower::getFlowerName ;// Allow call to  getFlowerName() method in the base class
};


class Rose:private Flower
{               // Inherit Flower as private
public:
string color;


    /* Initialize name and color data members */ 
Rose (string n = "No flower", string c = "Red"):color (c)
  {
  } 

void getFlowerName (Rose & r)
  {
    cout << r.color << endl;
  } 

using Flower::getFlowerName;    // Allow call to  getFlowerName() method in 
                                   the base class
};

派生类应调用基类:

class Rose : private Flower
{
public:
    std::string color;

    Rose (const std::string& n = "No flower",
          const std::string& c = "Red") : Flower(n), color(c)
    {
    }
// ...
};

目前,您隐式调用默认的Flower构造函数,但是它不存在。

创建Flower::Flower()默认构造函数。

Flower(){ name = NULL; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM