0

我在 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 对象的构造函数被声明为获取 char 变量。看到:

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

你能帮忙吗?

4

2 回答 2

0

假设这Game_Object是 的基类Person,您应该这样编写构造函数:

Person::Person(char in_code):Game_Object(in_code)
{

speed = 5;

cout << "Person constructed"<<endl;

}
于 2013-11-16T00:29:39.890 回答
0

我也有这个错误。我想到了。但首先我要写一些理论以便于理解。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;

当然,您可以指定自己的复制构造函数和复制赋值运算符或使用“删除”(在 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++ 好运,对丑陋的格式感到抱歉。

于 2015-02-01T11:34:48.763 回答