【问题标题】:C++ Error: conversion to non-scalar type requested?C++ 错误:请求转换为非标量类型?
【发布时间】:2015-12-01 06:01:26
【问题描述】:

我对 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

这是 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(); 
    }

}

这是主程序文件。

#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;

}

错误:请求从“oreilly_A1::FlexString*”转换为非标量类型“oreilly_A1::FlexString”。 "FlexString flex_str = new FlexString();"

【问题讨论】:

    标签: c++ class compiler-errors header include


    【解决方案1】:
    FlexString flex_str = new FlexString();
    

    是错误的,因为赋值的 RHS 是一个指向 FlexString 的指针,而 LHS 是一个对象。

    你可以使用:

    // Use the default constructor to construct an object using memory
    // from the stack.
    FlexString flex_str;
    

    // Use the default constructor to construct an object using memory
    // from the free store.
    FlexString* flex_str = new FlexString();
    

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多