【发布时间】:2016-04-01 19:15:25
【问题描述】:
我正在学习运算符重载。我创建了一个简单的类来测试它。
class Beer{
public:
Beer(int oner , int twor , string name){
this -> one = oner;
this -> two = twor;
this -> name = name;
};
int getOne(){
return this -> one;
};
int getTwo(){
return this -> two;
};
string getName(){
return this -> name;
};
Beer operator + (const Beer &a)const {
return Beer(5,two+a.two,"firstName");
};
Beer operator + (string a)const {
this -> name = this -> name +" "+a;
};
private:
int one;
int two;
string name;
};
我想弄清楚,如何用重载的操作数来中间化字符串。我声明了我的函数
Beer operator + (string a)const {
this -> name = this -> name +" "+a;
};
在传递 const 字符串时抛出错误。
我尝试过使用
Beer operator + ( const string *a)const {
swap(this -> name , this -> name + " " + a);
return *this;
};
抱怨一个是成本字符串,第二个是基本字符串。
这个想法很简单。
Beer one ( 5, 6, "one")
one + "two"
// one.name = "one two"
正确的做法是什么?
// 交换错误
error: no matching function for call to 'swap(const string&, std::basic_string<char>)'|
// 字符串错误
passing 'const string {aka const std::basic_string<char>}' as 'this' argument of 'std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(std::basic_string<_CharT, _Traits, _Alloc>&&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' discards qualifiers [-fpermissive]|
【问题讨论】:
-
请发布您得到的确切编译器错误。
-
顺便说一句,类方法定义末尾的分号是不用的。