3

我在实施我的课程时遇到了麻烦。它应该能够从 std::string 初始化。所以我写了一个副本(?)构造函数:

CVariable (std::string&, const int p_flags = 0);

我正在尝试制作一个 CVariable 对象:

MCXJS::CVariable s_var = (string)"good job";

我收到以下错误:

F:\Projekty\MCXJS\src\main.cpp|8|error: conversion from 'std::string' to non-scalar type 'MCXJS::CVariable' requested|

如何解决?

我正在寻找完全允许以下内容的解决方案

MCXJS::CVariable s_var = (string)"good job";

编辑:添加(几乎)完整的源代码:

变量.h

#ifndef CVARIABLE_H
#define CVARIABLE_H

#include <string>
#include <sstream>

namespace MCXJS
{
enum VARTYPE
{
    STRING = 0,
    INT = 1,
    FLOAT = 2
};

class CVariable
{
    public:
    VARTYPE Type () {return m_type;};
    std::string& Value () {return m_value;};
    bool SetType (VARTYPE);

    private:
    const int m_flags;
    VARTYPE m_type;
    std::string m_value;

    // ctors and operators
    public:
    CVariable (const int p_flags = 0);
    CVariable (CVariable&, const int);
    CVariable (std::string const&, const int);
    CVariable (const int&, const int);
    CVariable (const float&, const int);

    CVariable& operator= (const CVariable&);
    CVariable& operator= (const std::string&);
    CVariable& operator= (const int);
    CVariable& operator= (const float);
};
};

#endif // CVARIABLE_H

变量.cpp

#include "cvariable.h"

using namespace MCXJS;
using namespace std;

CVariable::CVariable (const int p_flags):
m_flags (p_flags)
{};

CVariable::CVariable (CVariable& p_var, const int p_flags = 0):
m_flags (p_flags),
m_type (p_var.Type()),
m_value (p_var.Value())
{};

CVariable::CVariable (std::string const& p_value, const int p_flags = 0):
m_flags (p_flags),
m_type (STRING),
m_value (p_value)
{};

CVariable::CVariable (const int p_value, const int p_flags = 0):
m_flags (p_flags),
m_type (INT)
{
std::ostringstream buffer;
buffer << p_value;
m_value = buffer.str();
};

CVariable::CVariable (const float p_value, const int p_flags = 0):
m_flags (p_flags),
m_type (FLOAT)
{
std::ostringstream buffer;
buffer << p_value;
m_value = buffer.str();
};

主文件

#include "cvariable.h"
#include <iostream>

using namespace std;

int main()
{
MCXJS::CVariable s_var = (string)"good job"; // error
cout << s_var.Value() << '\n';
return 0;
}

编辑:添加枚举 VARPARAM

编辑:好的,上面解决了,现在我有了这个:

cvariable.cpp|12|error: passing 'const MCXJS::CVariable' as 'this' argument of 'MCXJS::VARTYPE MCXJS::CVariable::Type()' discards qualifiers|
cvariable.cpp|13|error: passing 'const MCXJS::CVariable' as 'this' argument of 'std::string& MCXJS::CVariable::Value()' discards qualifiers|
4

3 回答 3

6

您需要通过 const 参考来获取它

CVariable (std::string const&, const int p_flags = 0);

通过非常量引用接受临时转换结果是没有意义的。之后对该参数的更改将丢失。通过使其成为 const 引用使其工作很容易,因此标准 C++ 只是禁止它。

于 2010-09-05T16:43:17.727 回答
0

MCXJS::CVariable s_var = (string)"干得好";

是错字吗?应该MCXJS::CVariable s_var = { 0, STRING, std::string("good job") };甚至更好,明确地 - MCXJS::CVariable s_var(std::string("good job"), 0);

于 2010-09-05T22:04:11.767 回答
0

您是否省略了在代码示例中添加“=”运算符重载的定义?您需要正确定义将字符串分配给对象时会发生什么。

于 2010-09-05T17:23:16.697 回答