使用私有派生类的构造函数初始化基类的数据成员 我是C++编程新手,我正在尝试执行下面的代码,但是 显示错误
调用“Flower::Flower()”Rose时没有匹配的函数(字符串n= “没有花”,字符串c=“红色”):颜色(c){} 即使我在我的类Flower中给出了参数化构造函数,它仍然表示没有匹配的函数调用使用私有派生类的构造函数初始化基类的数据成员 我是C++编程新手,我正在尝试执行下面的代码,但是 显示错误,c++,inheritance,constructor,C++,Inheritance,Constructor,调用“Flower::Flower()”Rose时没有匹配的函数(字符串n= “没有花”,字符串c=“红色”):颜色(c){} 即使我在我的类Flower中给出了参数化构造函数,它仍然表示没有匹配的函数调用 #include <iostream> #include <string> using namespace std; class Flower { public: string name; Flower (string n):name (n) { }
#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
};
#包括
#包括
使用名称空间std;
班级花
{
公众:
字符串名;
花(字符串n):名称(n)
{
}
void getFlowerName()
{
cout创建Flower::Flower()
默认构造函数
Flower(){ name = NULL; }
创建Flower::Flower()
默认构造函数
Flower(){ name = NULL; }
派生类应调用基类:
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
构造函数,但它不存在。派生类应调用基类:
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
构造函数,但它不存在。basic creator
?您指的是非参数化构造函数?被否决,因为“basic creator”和“basic constructor”都不是正确的术语。您可能指的是“default constructor”,我编辑了我的消息(basic creator->default constructor)。很抱歉弄错了英文名称。谢谢您的建议!basic creator
?您指的是非参数化构造函数?被否决,因为“basic creator”和“basic constructor”都不是正确的术语。您可能指的是“default constructor”,我编辑了我的消息(基本创建者->默认构造函数)。很抱歉弄错了英文名称。谢谢你的建议!现在工作正常。谢谢你的支持。但由于我是stack overflow新手,请告诉我我必须用正确的代码编辑我的答案,还是应该保持原样。你不应该编辑你的问题使已经给出的答案无效。@Ayush你应该怎么做如果有助于您解决问题,请接受其中一个答案。它现在运行良好。感谢您的支持。但是,由于我是堆栈溢出新手,请告诉我,我是否必须使用正确的代码编辑我的答案,或者我应该保持原样。您不应该编辑您的问题以使已给出的答案无效。@Ayush您应该做的是如果有助于解决问题,请接受其中一个答案