C++ 中的重载运算符<<

Overloading operator << in c++

本文关键字:lt 运算符 重载 C++      更新时间:2023-10-16

我试图重载操作符<<在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->访问成员)