您的位置:首页 > 编程语言 > C语言/C++

C++报错集锦

2016-04-26 18:32 330 查看
(一)invalid initialization of non-const reference of type ‘float&’ from a temporary of type ‘float’

代码如下:

#include <iostream>
using namespace std;

void update(float& i) {
cout << i << endl;
}

void g(double d, float r) {
update(2.0f);
update(r);
update(d);
}

int main(void) {
g(3.2, 1.3);
}

原因在于调用update(2.0f)和update(d)出错了:

对于普通的T&的初始式必须是一个类型T的左值;

对非const引用参数不允许做类型转换,非const引用不能引用一个常量。

这个问题有待进一步讨论。

(二)error: ‘cout’ was not declared in this scope

这真是个弱智问题,在文件头部加上

#include <iostream>
using namespace std;


(三)usestock0.cpp:7: error: request for member ‘acquire’ in ‘fluffy_the_cat’, which is of non-class type ‘Stock*’

这是因为自己用的是:

Stock *fluffy_the_cat = new Stock;
fluffy_the_cat.acquire("NanoSmart", 20, 12.50);
fluffy_the_cat.show();
fluffy_the_cat.buy(15, 18.125);
fluffy_the_cat.show();

问题出在fluffy实际上指针,而我在用的时候却把它当作普通的变量

解决办法:

Stock *fluffy_the_cat = new Stock;
(*fluffy_the_cat).acquire("NanoSmart", 20, 12.50);
(*fluffy_the_cat).show();
(*fluffy_the_cat).buy(15, 18.125);
(*fluffy_the_cat).show();

果然可以了,其实我是想测试如果用new新建对象,但是又不delete,这时候会不会调用析构函数,

最后是没有调用析构函数

(四)error: call of overloaded ‘max(int&, int&)’ is ambiguous

正在练习函数模版,结果报错

li7_2.cc: In function ‘int main()’:
li7_2.cc:19: error: call of overloaded ‘max(int&, int&)’ is ambiguous
li7_2.cc:7: note: candidates are: T max(T, T) [with T = int]
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_algobase.h:209: note: const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]

代码如下:

#include <iostream>
#include <string>

using namespace std;

// 声明了一个类模版
template <typename T> T max(T a, T b)
{
return a > b ? a : b;
}

int main()
{
int a, b;
cout << "Input two integers to a and b: ";
flush(cout);
endl(cout);
cin >> a >> b;
cout << "max(" << a << "," << b << ")=" << max(a,b) << endl;
}

原来是出现了函数实例模糊,std里面也有一个max函数模版,真是晕了,程序搞不清要用哪个,但是书上的程序居然是通的。真是醉了。
于是只好把那个max改为max1,程序就可以运行了。

(五)error: invalid operands of types ‘const char [2]’ and ‘char’ to binary ‘operator<<’

一般这个错误是cout << 输出时,<<少写了一个<

cout << "max1(" << "\'" << c << "\'" << "," <"\'" << d << "\'" << ")=" << max1(c,d) << endl;

(六)error: non-member function ‘T max(T*, int)’ cannot have cv-qualifier

错误代码

template <typename T> T max(T a[], int n) const
{
T tmp = a[0];
for(int i=1; i<n; i++)
{
if(a[i] > tmp)
tmp = a[i];
}
return tmp;
}

这里由于template max是一个函数模板,但是我却在后面加了一个const,天哪,const放在函数后面只能用于成员函数,表名调用这个函数的对象在函数执行的过程中并不改变。

而且函数模版的声明和定义必须是全局作用域,模板不能被声明成类的成员函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: