具有字符串函数的 C++ 类实现

c++ class implementation with string function

本文关键字:C++ 实现 函数 字符串      更新时间:2023-10-16

我需要为我的一个赋值实现一个类,而类中将字符串作为数据类型的函数之一不起作用

我的定义代码是:

#include <string>  
class expression {
public:
    expression();
    void promptUser();
    int getNum1();
    int getNum2();
    int calculate();
    st::string str;
    string numToString(int num);
    string opToString();
private:
    int num1;
    int num2;
    char op;
};

在我的实现文件中当我试图确定numTostring

string expression::numToString(int num) {
    string digit;
    ...

它说声明与头文件不兼容(我的类定义)

我不知道为什么,因为两个函数标题是相同的。

表达式.cpp(实现文件)的头文件是:

#include "expression1.h"
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

您的类使用非限定名 string ,但在任何封闭作用域中都没有定义string数据类型。命名空间std中定义了std::string数据类型。这看起来是您需要的类型:

std::string str;
std::string numToString(int num);
std::string opToString();

您可以通过指定 using 语句来避免在任何地方键入std::

using std::string;

但是您可能不想在头文件中执行此操作,因此请坚持完全限定类型。

如果要使用

,则需要使用 std::

例如,表达式类声明:

st::string str;
string numToString(int num);
string opToString();

应该是:

std::string str; // you typed st:: instead of std::
std::string numToString(int num); // lack of std::
std::string opToString(); // lack of std::

如果您不使用 2 个文件 (cpp + h) 来定义和声明您的类,那么您可以添加行

using namespace std;

就在你之后。这样,您就不必在每次尝试引用字符串和类似类型时键入 std:: 。但是,使用它通常被称为糟糕的"初学者"做法。

如果您确实使用 cpp+h,则只需在每个字符串类型之前添加 std:: 并使用命名空间 std 添加; 到您的 cpp 文件中。

如果您想了解更多信息,请阅读:
1. http://www.cplusplus.com/doc/tutorial/namespaces/
2. 为什么"使用命名空间标准"被认为是不好的做法?
3. 如何在C++中正确使用命名空间?

你还需要移动

#include "stdafx.h"

向上,所以它是包含的第一个标题。编译器会忽略该魔术行之前的所有内容。