剑指offer55 字符流中第一个不重复的字符(最典型错误)

典型并且基础的错误:

class Solution
{
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
        if(result[ch] == -1)
            result[ch] = index;
        else if(result[ch] >= 0)
            result[ch] = -2;
        index++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        char ch = '\0';
        int minindex = 999;
        for(int i = 0;i < 256;i++){
            if(result[i] >= 0){
                if(result[i] < minindex){
                    minindex = result[i];
                    ch = (char)i;
                }
            }
        }
        return ch;
    }
    int result[256];
    for(int i = 0;i < 256;i++)
        result[i] = -1;
    int index = 0;
};

错误显示:

编译错误:您提交的代码无法完成编译
In file included from a.cc:2:
./solution.h:29:5: error: expected member name or ';' after declaration specifiers
for(int i = 0;i < 256;i++)
^~~
a.cc:13:19: warning: comparison of integers of different signs: 'int' and 'size_t' (aka 'unsigned long') [-Wsign-compare]
for(int i = 0;i < strlen(str);i++) {
~ ^ ~~~~~~~~~~~
1 warning and 1 error generated.

c++的类中只能有属性和方法(也可以说函数)。

方法就是你定义的类中的那些实现函数,属性相当于类中的那些参数。

上面代码中报错的for循环,目的是对result数组进行初始化,但这个for循环不是一个函数,在类里面是不允许这种执行语句的,必须转换成函数才行。因为result本身是这个class类的属性,所以对result的初始化,其实相当于对类属性的初始化,可以通过构造函数来实现。

构造函数本身就是实现初始化类对象的数据成员。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值