【问题标题】:Redifiniton of variable with a different type用不同类型重新定义变量
【发布时间】:2013-11-16 00:20:08
【问题描述】:

我在 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;

你能帮忙吗?

【问题讨论】:

  • Game_Object obj(in_code);
  • 我们应该先假设Game_ObjectPerson 的基类,而您不小心把它放在Person 构造函数的主体中,而不是它所属的初始化列表中吗?无关:如果成员在类 def 中声明为 Cart_Point location;location = Cart_Point(); 将无用。它已经使用该默认值构建。事实上,我认为没有理由 all 该构造函数中的其他赋值不在 Game_Object 的初始化列表中,只有 cout &lt;&lt; ... 在实际主体中。

标签: c++ redefinition


【解决方案1】:

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

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

speed = 5;

cout << "Person constructed"<<endl;

}

【讨论】:

  • +1 如果它不是基类,Game_Object(in_code);这一行本身是没用的,应该去掉。
【解决方案2】:

我也有这个错误。我想到了。 但首先我要写一些理论以便于理解。 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 中“删除”的更多信息,您可以找到 here

所以在你的情况下编译器无法决定你实际调用的构造函数

Game_Object(in_code); 

line 因为有两种选择:要么调用 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++ 好运,对于难看的格式表示抱歉。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多