本文介绍了出现“ const”错误之前的预期主要表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助。我收到很多错误。

Please help. I am getting many errors.

sub2.cpp:在函数'int main()'中:
sub2.cpp:11:14:错误:转换无效从'const char *'到'char'[-fpermissive]
sub2.cpp:12:14:错误:从'const char *'到'char'[-fpermissive]
sub2的无效转换。 cpp:16:17:错误:'const'
sub2.c之前的预期主要表达式。cpp:16:36:错误:'const'
sub2.cpp之前的预期主要表达式:cpp:11:6:警告:未使用的变量'outer'[-Wunused-variable]
sub2.cpp:12:6:警告:未使用的变量'inner'[-Wunused-variable]
make: * [sub2]错误1

sub2.cpp: In function ‘int main()’: sub2.cpp:11:14: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive] sub2.cpp:12:14: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive] sub2.cpp:16:17: error: expected primary-expression before ‘const’ sub2.cpp:16:36: error: expected primary-expression before ‘const’ sub2.cpp:11:6: warning: unused variable ‘outer’ [-Wunused-variable] sub2.cpp:12:6: warning: unused variable ‘inner’ [-Wunused-variable] make: * [sub2] Error 1

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

char *Subtract(const char *outer, const char *inner);

int main()
{
    char outer = "Bookkepper";
char inner = "keep";

char *word = new char[50];

word = Subtract(const char &outer, const char &inner);

cout << word << endl;
return 0;
}


char *Subtract(const char *outer, const char *inner)
{
int olen = strlen(outer);
int first_occ_idx = -1;
for(int i=0; i < olen; i++){
    if(strncmp(outer+i, inner,strlen(inner)) == 0){
    first_occ_idx = i;
    }
}
if(first_occ_idx == -1){
    return NULL;
}
int ilen = strlen(inner);
int xx = olen - ilen;
char *newstr = new char[xx];
int idx = 0;
for(int i=0; i < first_occ_idx; i++){
    newstr[idx++] = outer[i];
}
for(int i=first_occ_idx+ilen; i < olen; i++){
    newstr[idx++] = outer[i];
}
newstr[idx] = '\0';
return newstr;
}


推荐答案

在C ++中,字符串文字如 Bookkepper (原文如此) const 个字符指针,它比C语言要严格一些。因此应该是:

In C++, string literals like "Bookkepper" (sic) are const character pointers, it's a little stricter than in C. So it should be:

const char *outer = "Bookkeeper"; // Note also spelling

,而不是:

char outer = "Bookkepper";

另外,调用函数时不包括类型,因此:

In addition, you don't include types when calling a function, so:

word = Subtract(const char &outer, const char &inner);

会更好一些,因为:

word = Subtract(outer, inner);






(分别是样式建议),表示 size 的事物的正确类型(例如字符串中的字符数)是 size_t 而不是 int


Separately (and these are style suggestions only), the correct type for things that represent sizes (such as number of characters in a string) is size_t rather than int.

通常,从 main()返回之前,显式清理所有动态内存是一种很好的方式。 ,您可以输入:

And it's usually considered good form to clean up all your dynamic memory explicitly so, before returning from main(), you could put:

delete[] word;

这篇关于出现“ const”错误之前的预期主要表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 06:43