简体   繁体   English

为什么g ++似乎混淆了数据类型?

[英]Why does it seem that g++ is mixing up data types?

I am currently making a big integer library for my college assignment. 我目前正在为我的大学作业制作一个大的整数库。 I am experiencing a problem with the following code: 我遇到以下代码的问题:

MyInteger::MyInteger(){ //default
    //some code
}
MyInteger::MyInteger(char *s){ //construct from string
    //some code
}
MyInteger::MyInteger(MyInteger &otherInt){ //copy constructor
    //some code
}
MyInteger MyInteger::parse(char *s){ //parse string and create new object
    return MyInteger(s);
}

I get the following error about the parse function: 我收到有关解析函数的以下错误:

MyInteger.cpp: In static member function ‘static MyInteger MyInteger::parse(char*)’:
MyInteger.cpp:34:20: error: no matching function for call to ‘MyInteger::MyInteger(MyInteger)’
  return MyInteger(s);
                    ^
MyInteger.cpp:34:20: note: candidates are:
MyInteger.cpp:23:1: note: MyInteger::MyInteger(MyInteger&)
 MyInteger::MyInteger(MyInteger &otherInt){ //copy constructor
 ^
MyInteger.cpp:23:1: note:   no known conversion for argument 1 from ‘MyInteger’ to ‘MyInteger&’
MyInteger.cpp:10:1: note: MyInteger::MyInteger(char*)
 MyInteger::MyInteger(char *s){ //construct from string
 ^
MyInteger.cpp:10:1: note:   no known conversion for argument 1 from ‘MyInteger’ to ‘char*’
MyInteger.cpp:4:1: note: MyInteger::MyInteger()
 MyInteger::MyInteger(){ //set string to 0
 ^
MyInteger.cpp:4:1: note:   candidate expects 0 arguments, 1 provided

Shouldn't it be using the 2nd constructor? 它不应该使用第二个构造函数吗? Either it is confusing the string with a MyInteger, or the string is being converted to a MyInteger somehow and then the compiler is trying to convert it again using the 3 candidates that it has listed. 要么将字符串与MyInteger混淆,要么将字符串以某种方式转换为MyInteger,然后编译器尝试使用列出的3个候选对象再次将其转换。 A similar error is occuring with the overloaded + operator. 重载的+运算符也会发生类似的错误。

Please tell me what I am doing wrong. 请告诉我我在做什么错。

It's not the MyInteger(s) that's the problem. 问题不是MyInteger(s) It constructs that temporary object. 它构造该临时对象。 It's the attempt to return this temporary object that is the problem. 试图返回这个临时对象就是问题所在。 You are returning by value, which means that a copy needs to be made, yet your copy constructor takes a MyInteger& , which is unable to bind to temporary objects (rvalues). MyInteger&值返回,这意味着需要创建一个副本,但是您的副本构造函数使用MyInteger& ,它无法绑定到临时对象(rvalues)。 Your copy constructor should have parameter of type const MyInteger& instead, which will allow it to do so. 您的副本构造函数应使用const MyInteger&类型的参数,这将允许它这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM