【发布时间】:2020-12-30 03:18:50
【问题描述】:
我已经声明了一个类 Products 和另一个类 CD,该类 CD 继承了类 Products。 现在我已经声明了一个构造函数来更新它的值。我收到一个错误
#include <iostream>
#include <string>
class Products
{
private:
std::string name;
std::string type;
double price;
public:
virtual std::string getname();
virtual double getprice();
virtual void show();
std::string gettype()
{
return type;
}
};
class CD: public Products
{
private:
std::string artist;
std::string studio;
public:
CD(std::string sname,double sprice,std::string sartist,std::string sstudio)
{
this->type = "CD";
this->name = sname ;
this->price = sprice;
this->artist = sartist;
this->studio = sstudio;
}
void show()
{
std::cout<<"\nName of the CD:\t"<<this->name;
std::cout<<"\nArtist of the CD:\t"<<this->artist;
std::cout<<"\nStudio of the CD:\t"<<this->studio;
std::cout<<"\nPrice of the cd:\t"<<this->price;
}
};
int main()
{
CD obj("Oceans",49,"somesinger","somestudio");
}
错误:
在构造函数中'CD::CD(std::string, double, std::string)';
'std::string Products::type' 在这个上下文中是私有的
this->type="CD";
'std::string Products::name' 在此上下文中是私有的
this->name=sname;
'double Products::price' 在此上下文中是私有的
this->price= sprice;
基本上它不会对 CD 类的私有数据成员给出错误,而只是对从 Products 类继承的数据成员给出错误
【问题讨论】:
-
例如“类型是私有类成员”的哪一部分你不清楚?
-
CD无权访问其基类的私有成员。这就是private的意义所在。 -
type 只是一个数据成员@Sam Varshavchik
-
也许你的意思是
protected就像“派生类可以完全访问这些字段”而不是private意思是“离开我的草坪你们这些笨孩子!” -
打开你的课本,阅读
private、protected和public之间的区别。
标签: c++ class inheritance