具有不同类型的变量的 Redifiniton

Redifiniton of variable with a different type

本文关键字:变量 Redifiniton 同类型      更新时间:2023-10-16

我在Xcode上收到以下错误:关于我的变量"in_code"和我的类"Game_Object"

使用不同类型"Game_Object"与"char"重新定义"in_code

"

这是我的另一个类 Person 的构造函数

Person::Person(char in_code)
{
Game_Object(in_code);     -> HERE IS WHERE I AM GETTING THE ERROR!!
speed = 5;
cout << "Person constructed"<<endl;
}

但是,我的游戏对象构造函数被声明为获取字符变量。请参阅:

Game_Object::Game_Object(char in_code)
{
display_code = in_code;
state = 's';
id_num = 0;
location = Cart_Point();
cout<<"Game_Object constructed."<<endl;

你能帮忙吗?

假设Game_ObjectPerson的基类,你应该像这样编写构造函数:

Person::Person(char in_code):Game_Object(in_code)
{
speed = 5;
cout << "Person constructed"<<endl;
}

我也有这个错误。我想通了。但首先,我必须写一些理论以便于理解。C++中有两个功能可以在编译时隐式创建额外的代码:

1) 复制构造函数和复制赋值运算符由编译器创建,如果您没有为类指定它们。在实现部分,它递归复制每个成员。

2) 如果你有一个构造函数,其中包含任何类型的一个参数,那么编译器还会创建一个具有相同参数的赋值运算符。在实现部分,它会创建您类型的新实例并将其分配给您的变量。

下面的示例代码对此进行了说明:

class GameObject{
public:
    GameObject(int iD):innerData(iD){
        //..
    }
    int innerData;
};
//  Create a new object using constuctor specified by me..
GameObject gameObject(5);
std::cout<<"gameObject = "<<gameObject.innerData<<std::endl;
//  Create the second object with different data..
GameObject gameObject2(6);
std::cout<<"gameObject2 = "<<gameObject2.innerData<<std::endl;
//  Next line compiles well cause compiler created
//  GameObject& operator=(const GameObject&) for us.
gameObject2=gameObject;
std::cout<<"gameObject2 = "<<gameObject2.innerData<<std::endl;
//  Next line also compiles well cause compiler created
//  GameObject& operator=(int iD) using GameObject(int iD)
//  as a reference.
gameObject2=3;
std::cout<<"gameObject2 = "<<gameObject2.innerData<<std::endl;

当然,您可以指定自己的复制构造函数和复制赋值运算符,或者使用"delete"(在 C++11) 关键字中显示)来删除复制类的任何实例的功能。有关 C++11 中"删除"的更多信息,您可以在此处找到。

因此,在您的情况下,编译器无法决定您实际调用的构造函数

Game_Object(in_code); 

行原因有两个选项:要么调用Game_Object(char)构造函数,要么调用Game_Object(Game_Object(char))构造函数。这听起来很愚蠢,但这些结构对于编译器来说是不同的。

因此,解决问题所需要做的就是使用类型转换运算符显式指定参数的类型

Person::Person(char in_code)
{
Game_Object(char(in_code));    
speed = 5;
cout << "Person constructed"<<endl;
}

祝C++好运,对不起,格式丑陋。