我试图了解我们在C ++程序中通常会遇到的错误的含义。
编译程序时出现错误(我是故意犯此错误,请不要告诉我如何更正该错误),并且存在一条注释:
note: no known conversion for argument 1 from ‘int’ to ‘const account&’
我想了解此注释的含义。
我的程序是:
#include<iostream>
class account
{
private:
int a_no;
public:
account()
{
a_no = 0;
}
void showData()
{
std::cout<<"\n account number = "<<a_no<<std::endl;
}
};
int main()
{
account a1;
a1.showData();
account a2(2);
a2.showData();
return 0;
}
我知道我还没有定义一个可以接受一个参数的构造函数,这样做可以消除我的错误。
好的,在编译时我得到:
file1.cpp: In function ‘int main()’:
file1.cpp:20:17: error: no matching function for call to ‘account::account(int)’
account a2(2);
^
file1.cpp:20:17: note: candidates are:
file1.cpp:7:9: note: account::account()
account()
^
file1.cpp:7:9: note: candidate expects 0 arguments, 1 provided
file1.cpp:2:7: note: account::account(const account&)
class account
^
file1.cpp:2:7: note: no known conversion for argument 1 from ‘int’ to ‘const account&’
我想知道最后一行的含义是什么file1.cpp:2:7: note: no known conversion for argument 1 from ‘int’ to ‘const account&’
?
1)您已经知道您没有带int的构造函数。2)您知道您正在尝试使用int构造帐户。3)如果您不这样做,则编译器将创建默认的复制构造函数,赋值运算符4)默认的复制构造函数将const引用引用到account
那么这里发生了什么?因为只有一个默认构造函数,并且您正在使用一个参数进行构造,所以编译器认为您要复制构造。当您给他一个int作为复制构造函数的参数时,编译器会尝试将int转换为一个帐户-这是行不通的,并且他告诉您:“无法从int转换为account”
要知道这一点非常重要,因为这是许多错误的来源。您可能不想调用复制构造函数。但是,如果编译器确实找到了将您用作参数的类型转换为account的方法,会发生什么?一团糟....
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句