具有不同类型的变量的 Redifiniton
Redifiniton of variable with a different type
我在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_Object
是Person
的基类,你应该像这样编写构造函数:
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++好运,对不起,格式丑陋。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 具有不同类型的变量的 Redifiniton