【发布时间】:2017-10-19 16:38:13
【问题描述】:
下面是我的代码:
class Pulley{
private:
int noOfTeeth;
public:
Pulley();
Pulley(int teeth);
~Pulley();
void show();
};
Pulley::Pulley()
{
cout << "Pulley constructor called!";
noOfTeeth = 0;
}
Pulley::Pulley(int teeth)
{
cout << "Pulley constructor called!";
noOfTeeth = teeth;
}
void Pulley::show()
{
cout << "\n\nNo of Teeths of Pulley: " << noOfTeeth;
}
Pulley::~Pulley()
{
}
class GearBox{
private:
char *transmission;
Pulley p;
public:
GearBox();
GearBox(char *trans, int pTeeth);
~GearBox();
void show();
};
GearBox::GearBox(): p()
{
cout << "Gearbox constructor called!";
transmission = NULL;
}
GearBox::GearBox(char *trans, int pTeeth): p(pTeeth)
{
cout << "Gearbox constructor called!";
if(trans != NULL)
{
transmission = new char[strlen(trans)+1];
strcpy(transmission, trans);
}
else
{
transmission = NULL;
}
}
void GearBox::show()
{
cout << "\n\nTransmission of vehicle: " << transmission;
p.show();
}
GearBox::~GearBox()
{
}
class Vehicle{
private:
char *model;
char *color;
GearBox g;
public:
Vehicle();
Vehicle(char *mod, char *col, char *gr);
Vehicle(const Vehicle &vh);
~Vehicle();
void show();
};
Vehicle::Vehicle(): g()
{
cout << "Vehicle constructor called!";
model = NULL;
color = NULL;
}
Vehicle::Vehicle(char *mod, char *col, char *gr): g(gr)
{
cout << "Vehicle constructor called!";
if(mod != NULL)
{
model = new char[strlen(mod)+1];
strcpy(model, mod);
}
else
{
model = NULL;
}
if(col != NULL)
{
color = new char[strlen(col)+1];
strcpy(color, col);
}
else
{
color = NULL;
}
}
void Vehicle::show()
{
cout << "\n\nModel of Vehicle: " << model;
cout << "\n\nColor of Vehicle: " << color;
g.show();
}
int main()
{
Pulley p(20);
GearBox g("Manual", p);
Vehicle V("Honda", "Black", g);
V.show();
system("PAUSE");
}
现在,当我运行这段代码时,我得到了很多错误,我不知道这些是什么以及如何解决它们。我理解的一个错误是复制构造函数,所以任何人都可以向我解释如何为指向字符transmission, model and color 的指针编写复制构造函数。还告诉我如何解决其他错误。非常感谢。
【问题讨论】:
-
编写代码时,先从小而简单的完美工作开始,然后逐渐增加一点复杂性。如果你对这么多代码有很多错误,那是因为你没有在它们出现时解决它们。 永远不要添加不起作用的代码。我建议您尽可能简化此代码,同时仍然会出现一些错误;您可能会发现错误变得很明显,否则您可以发布一个更简单的示例。
-
存储字符串时,使用std::string。不要编写析构函数或复制运算符。委托给 std::string、std::vector、std::unique_ptr 等。
-
现在,当我运行这段代码时,我得到了很多错误,我不知道这些是什么以及如何解决它们。 从这个声明中不清楚是否您遇到了编译错误(如果是,这些错误是什么?),或者您的代码在运行时失败(如果是,您是否尝试使用调试器单步执行您的代码,以找出失败的原因?)。
-
在实现构造函数、析构函数和赋值运算符时,理解the rules of 0/3/5 非常重要。遵循此建议可能会解决您的问题。
-
为什么调用main中的构造函数调用不匹配调用的构造函数?
标签: c++ copy-constructor composition