2016-10-01 152 views
0

HI。在我的问题之前,我查看了其他线程有同样的错误,没有为我工作。 我的问题代码是in >> a.name >> a.extension;。当我测试自己时,如果我将变量的类型从string更改为char,它将起作用,但我无法使其与string类型的值一起工作。错误C++ 2679(二进制'>>':找不到操作符需要'const std :: string'类型的右侧操作数(或者没有可接受的转换))

我做错了什么? 下面就compillation(Visual Studio的2015年)

错误C2679二进制“>>”完全错误代码:没有操作员发现这需要右手 数类型“字符串常量的std ::”的(或有不可接受 转换)

在此先感谢。这里

#include <iostream> 
#include <ctime> 
#include <string> 
using namespace std; 

class Soft { 
private: 
    int *size; 
    time_t *dateTime; 
public: 
    string name; 
    string extension; 
    Soft(); 
    Soft(string, string); 
    Soft(const Soft&source); 
    ~Soft(); 

    friend istream& operator>> (istream& in, const Soft& a) 
    { 
     in >> a.name >> a.extension; 
     return in; 
    }; 

    void changeName(string); 
    void changeExtension(string); 
}; 

Soft::Soft() { 
    size = new int; 
    *size = 0; 
    name = string(""); 
    extension = string(""); 
    dateTime = new time_t; 
    *dateTime = time(nullptr); 
} 

Soft::Soft(const Soft&source) { 
    name = source.name; 
    extension = source.extension; 
    size = new int; 
    *size = *source.size; 
    dateTime = new time_t; 
    *dateTime = time(nullptr); 
} 

Soft::Soft(string a, string b) { 
    name = a; 
    extension = b; 
    dateTime = new time_t; 
    *dateTime = time(nullptr); 
} 

Soft::~Soft() { 
    delete[] size; 
    delete[] dateTime; 
} 

void Soft::changeExtension(string a) { 
    extension = a; 
} 
void Soft::changeName(string a) { 
    name = a; 
} 


int main() { 

    Soft a; 

    getchar(); 
    getchar(); 
    return 0; 
} 

回答

3

的关键词是const,这意味着东西不能被修改。

您正在尝试修改const的东西。你不能这样做。

你的功能,如一般任何operator>>,应声明如下:

friend istream& operator>>(istream& in, Soft& a) 

我已经作出的变化是删除const

顺便说一句,我没有看到任何理由让你的成员变量sizedateTime成为指向动态分配整数的指针。如果你只是使它们成为正常的整数,你的代码将会更简单。因为该运营商改变了值,从而试图改变一个恒定值是一个试图打破规则

+0

我没有看到任何,但我的学校的老师希望与指针的一切......这是写明确使用指针所有变量 –

+3

@ M.Eugen:这是可笑的。你被教导如何做错了。 :( –

+0

@LightnessRacesinOrbit:你没有学到的东西“可变”关键字呢?他可以宣布他的会员数据,可变的,那么他的例子将正常工作 – Raindrop7

0

赋值运算符的左值不能是恒定的。

看看插入操作:

ostream& operator <<(ostream&, const myCalss&); // here const is ok 

这里,因为插入运算符只是用来打印值(常量和非const)不改变他们这是确定。

***,如果你的真正需要突破常量性的规则,申报您的会员数据作为可变:

 mutable int *size; 
    mutable time_t *dateTime; 

但在你的例子中,你不必这样做,我只是解释说,你可以改变cont变量。

相关问题