问题描述
我正在为 uni 做一个项目,我正在考虑一个简单的游戏,您可以使用 Visual Studio 代码建造船只并与其中的 6 个舰队作战,但是当我尝试构建一个对象时,我总是遇到错误“Ship”类中不正确的复制构造函数。我虚心寻求帮助。(这个变化->是因为我正在尽一切努力让它工作)
String^ tekst = MyForm2::textBox1->Text;
int FP = int::Parse(MyForm2::textBox2->Text);
int Armor = int::Parse(MyForm2::textBox3->Text);
int Speed = int::Parse(MyForm2::textBox4->Text);
int AA = int::Parse(MyForm2::textBox5->Text);
int special= int::Parse(MyForm2::textBox6->Text);
int hp = 15;
if (radioButton1->Checked == true)
{
Ship s_1 = Ship (tekst,FP,hp,Armor,Speed,AA);
}
ref class Ship
{
public:
String^ nazwa;
int FP;
int HP;
int ARMOR;
int SPEED;
int AA;
Ship() {};
Ship(String^ new_nazwa,int new_fp,int new_hp,int new_armor,int new_speed,int new_aa)
{
nazwa = new_nazwa;
FP = new_fp;
HP = new_hp;
ARMOR = new_armor;
SPEED = new_speed;
AA = new_aa;
};
};
ref class Destroyer : public Ship
{
public:
Destroyer() {};
Destroyer(String^ new_nazwa,int new_torp,int new_aa)
{
nazwa = new_nazwa;
FP = new_fp;
HP = new_hp;
ARMOR = new_armor;
SPEED = new_speed;
TORP = new_torp;
AA = new_aa;
};
int TORP;
};
ref class Battleship : public Ship
{
public:
Battleship(String^ new_nazwa,int new_sec_fp,int new_aa)
{
this->nazwa = new_nazwa;
this->FP = new_fp;
this->HP = new_hp;
this->ARMOR = new_armor;
this->SPEED = new_speed;
this->Sec_FP = new_sec_fp;
this->AA = new_aa;
};
int Sec_FP;
};
ref class Carrier : public Ship
{
public:
Carrier(String^ new_nazwa,int new_aa)
{
this->nazwa = new_nazwa;
this->FP = new_fp;
this->HP = new_hp;
this->ARMOR = new_armor;
this->SPEED = new_speed;
this->TORP = new_torp;
this->AA = new_aa;
};
int TORP;
};
ref class Cruiser : public Ship
{
public:
Cruiser(String^ new_nazwa,int new_aa)
{
this->nazwa = new_nazwa;
this->FP = new_fp;
this->HP = new_hp;
this->ARMOR = new_armor;
this->SPEED = new_speed;
this->AA = new_aa;
};
};
解决方法
Ship s_1 = Ship (tekst,FP,hp,Armor,Speed,AA);
此行尝试使用调用复制构造函数的语法在堆栈上创建引用类型 Ship
的实例。这是自 VS2005 以来允许的,但有几个警告(引用自 C++ Stack Semantics for Reference Types):
当您使用堆栈语义创建引用类型的实例时,编译器会在垃圾收集堆上内部创建实例(使用 gcnew)。 [...] 编译器不会为引用类型生成复制构造函数。
以下是使其工作的可能方法(不讨论创建具有堆栈语义的 ref 类型的一般优点,这已在上一个链接中介绍)。
-
不要使用堆栈语义。相反:
Ship ^s_1 = gcnew Ship(tekst,AA);
-
使用堆栈语义直接构造,而不是复制构造:
Ship s_1(tekst,AA);
-
使用发布的代码,但为
ref class Ship
定义一个复制构造函数:Ship(const Ship %other) { nazwa = other.nazwa; /* ... */ }