cam*_*lly 2 c++ compiler-errors header class include
我是C++的新手,我正在尝试使用名为FlexString的容器类构建链接列表.在main()中,我想通过简单地说:"FlexString flex_str = new FlexString();"来实例化FlexString类.调用构造函数等但它不会编译,错误在底部.这是我的代码:
//FlexString.h file
#ifndef FLEXSTRING_CAMERON_H
#define FLEXSTRING_CAMERON_H
#include "LinkedList.h"
#include <string>
using namespace std;
using oreilly_A1::LinkedList;
namespace oreilly_A1 {
class FlexString {
public:
FlexString();
void store(std::string& s);
size_t length();
bool empty();
std::string value();
size_t count();
private:
LinkedList data_list;
};
}
#endif
Run Code Online (Sandbox Code Playgroud)
这是FlexString类的.cpp文件:
#include "FlexString.h"
#include "LinkedList.h"
#include <string>
using namespace std;
namespace oreilly_A1 {
FlexString::FlexString() {
}
void FlexString::store(string& s) {
data_list.list_head_insert(s);
}
std::string value() {
data_list.list_getstring();
}
}
Run Code Online (Sandbox Code Playgroud)
这是主程序文件.
#include <iostream>
#include <cstdlib>
#include "FlexString.h"
using namespace std;
using oreilly_A1::FlexString;
int main() {
FlexString flex_str = new FlexString();
cout << "Please enter a word: " << endl;
string new_string;
cin >> new_string;
flex_str.store(new_string);
cout << "The word you stored was: "+ flex_str.value() << endl;
}
Run Code Online (Sandbox Code Playgroud)
错误:从'oreilly_A1 :: FlexString*'转换为非标量类型'oreilly_A1 :: FlexString'请求."FlexString flex_str = new FlexString();"
FlexString flex_str = new FlexString();
Run Code Online (Sandbox Code Playgroud)
这是错误的,因为赋值的RHS是指向FlexStringLHS是一个对象的指针.
您可以使用:
// Use the default constructor to construct an object using memory
// from the stack.
FlexString flex_str;
Run Code Online (Sandbox Code Playgroud)
要么
// Use the default constructor to construct an object using memory
// from the free store.
FlexString* flex_str = new FlexString();
Run Code Online (Sandbox Code Playgroud)