C++ 中的重载运算符<<
Overloading operator << in c++
我试图重载操作符<<在c++中。下面是我的代码:
toString和<<都在VipCustomer
的。cpp文件中string VipCustomer::toString(){
return "VIP Name: " + this->m_cuName + " Bill: "
+ to_string(this->m_cuCurrentBiil);
}
ostream& operator<< (ostream& out, VipCustomer *obj){
return out << obj->toString();
}
int main(){
VipCustomer * cus2 = new VipCustomer("bob", 10);
cout << cus2 << endl;
}
我得到的输出是cus2的地址,我做错了什么?
关于@ tc的注释,改成:
int main (){
VipCustomer cus2("bob", 10);
cout << &cus2;
}
在cpp文件中:
string VipCustomer::toString(){
return "VIP Name: " + this->m_cuName + " Bill: " + to_string(this->m_cuCurrentBiil);
}
ostream& operator<< (ostream& out, VipCustomer &obj){
return out << obj.toString();
}
在.h文件中:
class VipCustomer :public Customer
{
public:
VipCustomer();
VipCustomer(std::string name ,int bill);
~VipCustomer();
void addtoBill(int amount);
string toString();
};
还是同样的问题
问题是你使用了指针。除非必要,否则你不应该使用它们,而在你的情况下,这不仅是不必要的,而且是错误的。需要将重载操作符从指针改为引用:
ostream& operator<< (ostream& out, VipCustomer &obj){
和对象的构造不应该使用动态内存:
VipCustomer cus2("bob", 10);
(最好将操作符的实参设置为const引用,但是您还需要将toString
设置为const——这是应该的。)不需要使用this->
访问成员)
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多