简体   繁体   English

C ++:使用函数声明一个处理字符串的类

[英]C++: declaring a class with functions, that handle string

I haven`t found answer to my question using search, though I thought it is simple and popular. 尽管我认为这很简单而且很受欢迎,但我还没有使用搜索找到问题的答案。 Anyway, my question is: I have got a header file, which declares a class and functions in it. 无论如何,我的问题是:我有一个头文件,其中声明了一个类和函数。 It looks like that: 看起来像这样:

#ifndef SOME_CLASS_H
#define SOME_CLASS_H

#include <string>

class mySomeClass
{
    public:

    bool a_func(string & myString, unsigned long int & x);
    void b_func(string & myString, unsigned long int & x);
    void c_func(string & myString, unsigned long int & x);

    void another_func(string & myString, string & myString2);

    }

#endif // SOME_CLASS_H

I think function definitions do not actually matter now. 我认为函数定义现在实际上并不重要。

When compiling, compiler tells that 'string' has not been declared , even though I have added #include <string> . 编译时,即使我添加了#include <string> ,编译器也会告诉您尚未声明'string' How can I solve this except for rewriting functions to use char* instead. 除了改写使用char*函数外,我该如何解决。 Thank you in advance. 先感谢您。

Done. 做完了 Thanks everybody. 谢谢大家。

Problem: the string class resides in namespace std . 问题: string类位于命名空间std

Solutions: 解决方案:

  1. Best solution: simply use std::string instead of string in your function declarations. 最佳解决方案:在函数声明中只需使用std::string而不是string
  2. Another, less optimal solution: add using namespace std; 另一个不太理想的解决方案: using namespace std;添加using namespace std; after the include directive (for an explanation of the drawbacks/dangers of using , see the link in sbi's comment). 之后include指令(用于的缺点/危险的说明using ,请参阅SBI的评论的链接)。

string是在命名空间std声明的,因此您必须将函数声明更改为

bool a_func(std::string & myString, unsigned long int & x);

The type string that you're willing to use is declared in a namespace called std . 您愿意使用的类型string在名为std的命名空间中声明。

Use std::string 使用std::string

The type defined in <string> is called std::string, not just string. <string>中定义的类型称为std :: string,而不仅仅是string。

#ifndef SOME_CLASS_H 
#define SOME_CLASS_H 

#include <string> 

class mySomeClass 
{ 
    public: 

    bool a_func(std::string & myString, unsigned long int & x); 
    void b_func(std::string & myString, unsigned long int & x); 
    void c_func(std::string & myString, unsigned long int & x); 

    void another_func(std::string & myString, std::string & myString2); 

    } 

#endif // SOME_CLASS_H

put

using namespace std

under

#include <string>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM