【发布时间】:2017-02-24 03:30:56
【问题描述】:
该程序的目的是生成扬声器外壳的模拟脚本。
因此我有一个定义演讲者的班级演讲者。
一个父类外壳,包含所有外壳的公共参数。
具有自身特殊属性的子类。
使用多态性和继承,我获得了第一个运行良好的程序,但我每次都需要重新计算外壳的基本属性:
class speaker
{
}
class Enclosure
{
int m_boxHeight;
speaker * m_speakerBass;//...
public://some functions
}
class closedBox : public Enclosure
{
public:
closedbox(speaker &speakerbass):Enclosure(speakerbass)// some functions
protected:
int paramclosed1;//...
}
int main()
{
speaker speakerbass;
cout <<endl<< "Please choose in the available enclosure proposals" << endl;
cout << "1 Closed box enclosure" << endl;
// cout << "2 Bass reflex enclosure" << endl;
// cout << "3 and so on..." << endl;
int choice;
cin>>choice;
switch (choice)
{
case 1:
closedbox * ClBox2Simu;
ClBox2Simu= new closedbox(speakerbass);
delete ClBox2Simu;
break;
case 2:
//... same but with bassreflex class child
break;
default:
cout<<"Then good bye";
}
return 0;
}
在我的程序中,父类的成员数据可以提供给子类。我的意思是,Enclosure 的框尺寸在每个子类bassreflex 或closedbox 中都是相同的。
如果有办法,我现在会这样做:
创建父类
进行第一次初始一般计算
使用父参数创建子节点(问题)
这基本上意味着 child=parent 这是被禁止的。 在这段代码的想法中:
class speaker
{
public: // some functions
protected:
int fs;
int paramSpeaker2; //...
}
class Enclosure
{
public: //some common function
protected:
int m_boxHeight;
speaker *m_speakerBass //...
}
class closedBox : public Enclosure
{
public:
closedbox(); // some functions
protected:
int paramclosed1; //...
}
class bassreflex : public Enclosure
{
public:
bassreflex(); // some functions
protected:
int paramclosed1; //...
}
int main()
{
Enclosure initialBox;// calculate dimension,choose speaker...
closedbox * ClBox2Simu;
ClBox2Simu= initialBox;// child= parent which is forbidden
//do stuff concerning closedbox
delete ClBox2Simu;
bassreflex * BassReflex2Simu;
BassReflex2Simu= initialBox; //forbidden
//do stuff concerning bassreflex
delete BassReflex2Simu;
//... and so on for other child class using enclosure
delete initialBox
return 0;
}
希望清楚!
【问题讨论】:
-
为什么不直接初始化子类呢?是时候阅读Constructors and member initializer lists
-
我不明白您在哪里(或为什么)“重新计算基本属性”?
-
第一个例子中的动态分配是完全没有必要的。
-
@Danh,@UnholySheep 这就是我在第一个程序中所做的,我想在第二个中做的是计算公共属性,例如:
Enclosure commonEnclosure然后声明子类@987654328 @,bassreflex box2与父commonEnclosure的参数。 -
@Boulgour 你可以在基本构造函数中进行常见的初始化,对吧?
标签: c++ inheritance