2016-10-01 155 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變量。

相關問題