具有字符串函数的 C++ 类实现
c++ class implementation with string function
我需要为我的一个赋值实现一个类,而类中将字符串作为数据类型的函数之一不起作用
我的定义代码是:
#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"
向上,所以它是包含的第一个标题。编译器会忽略该魔术行之前的所有内容。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的