“std”不会在函数之前命名类型和预期的初始值设定项

‘std’ does not name a type and expected initializer before a function

本文关键字:类型 std 函数      更新时间:2023-10-16

下面是我的代码,它试图将字符串"key=value"分成两个子数组"key"和"value",以下是错误:

string2StringPair.cc:9:3:错误:"std"未命名类型;string2StringPair.cc:10:3:错误:"std"未命名类型;string2StringPair.cc:13:12:错误:"string2StringPair"之前的预期初始值设定项

#ifndef __PARSE_H_
#define __PARSE_H_
#include "cppstd.hh"
#include <string>
using namespace std;
struct StringPair{
  std:string key; 
  std:string value;
}
StringPair string2StringPair (char* str[]){
  std:string x, y;
  x = ""; y = "";
  for (int i=0;i<str.length();i++){
    if str[i]=="="{
        for (int j=0;j<i;j++){
      x=x+str[j];
    }
        for (int k=(i+1);k<str.length();k++){
      y=y+str[k];
    }
        break; 
    }
  }
  if ((x=="") && (y=="")){
    cout<<"ERROR: There is no = in the input string!"<<endl;
  }
  StringPair tmp;
  tmp.key = x; 
  tmp.value = y;
  return tmp;
} 
#endif
int main(int argc, char *argv[]){
  StringPair pair;
  pair.string2StringPair(argv[1]);
  cout<<"The pair is "<<pair<<endl;
  return 0;
}

如果您能帮助我修复错误,将不胜感激。

当我更改为

std::string key; 
std::string value;

不再有"标准"错误。为什么??

为什么在 string2StringPair 之前需要初始值设定项?我虽然我已经有一个:字符串对?

你错过了这个:

std::而不是std:

编辑

当我更改为

标准::字符串键; 标准::字符串值;没有更多的"标准"错误。 为什么??

因为C++编译器期望在:后按照C++标准中scope resolution规则的定义进行另一个:

命名空间

和后面的内容之间的分隔符是C++中的两个冒号字符。

因此,您需要以下内容:

std::string key;

或者,既然你说的是using namespace std,你实际上可以完全省略std::前缀。但是,using namespace std不被视为良好的编码实践。

长话短说:删除using namespace std;并使用std::前缀。

此外,对于包含保护,不要使用带有双下划线(甚至单下划线)的标识符。关于在C++标准中保留标识符的前导下划线有相当严格的规定。虽然您在使用它们时可能会逃脱,但绝对不推荐。

只需使用

#ifndef PARSE_H
#define PARSE_H

std:: 而不是 std: //note :: is two times.

如果您使用的是命名空间 std,则无论如何都不需要使用 "std::"。选择一种编程约定。

至于您编辑的问题,为什么在使用后没有更多的错误:: ,

"::" 用于访问类/结构或命名空间的静态变量和方法。它还通常用于从另一个范围访问变量和函数。复习C++的基础知识,否则你进步得越多就越难。

有许多错误。

您需要在std使用位置后使用两个冒号。

struct声明后需要跟一个分号。

struct StringPair {
    std::string key;
    std::string value;
};  // <-- add semi-colon here

你的意思是使用 std::string 作为 string2StringPair() 的输入,因为你在该函数中使用str就像一个对象一样。

StringPair string2StringPair (std::string str){

您需要使用 str.size() 来获取字符串的长度,字符比较使用单引号,而不是双引号。

for (int i=0 ; i< str.size();i++){  // use str.size() 
    if(str[i] == '=') {          // "=" is a string.  '=' is a single character.

在你的main()函数中,你的意思是将string2StringPair()的结果分配给pairpair没有任何方法可以调用。

pair = string2StringPair(argv[1]);
相关文章: