gpt4 book ai didi

c++ - 蹩脚的运算符重新定义错误

转载 作者:太空宇宙 更新时间:2023-11-04 12:26:52 25 4
gpt4 key购买 nike

抱歉,它很蹩脚,但我无法弄清楚:

class Address {

public:

uint32_t addr;
uint16_t port;

public:
Address();
Address(uint32_t addr, uint16_t port);
Address(const Address & src);
Address& operator=(const Address &src);
bool isNull();

friend std::ostream& operator<<(std::ostream& os, const Address& addr);
friend std::ostream& operator<<( const Address& addr, std::ostream& os);
};


std::ostream& operator<<( std::ostream& os, const Address& addr){
return os << " ( " << addr.addr << " : " << addr.port << " ) ";
}

std::ostream& operator<<( const Address& addr, std::ostream& os){

return os << addr;
}

说:

../src/streamShare/types.h: In function ‘std::ostream& streamShare::operator<<(std::ostream&, const streamShare::Address&)’:
../src/streamShare/types.h:46: error: no match for ‘operator<<’ in ‘os << " ( "’
../src/streamShare/types.h:45: note: candidates are: std::ostream& streamShare::operator<<(std::ostream&, const streamShare::Address&)

也许只是我在周日宿醉中......但是嘿ostream& << "oihoih"应该工作!!!

最佳答案

以下代码在 gcc 4.3.2 上对我来说编译得很好。 (我定义了构造函数以使其正确链接。)

#include <iostream>

class Address
{
public:

uint32_t addr;
uint16_t port;

public:
Address() : addr(0), port(0) { }

Address(uint32_t addr, uint16_t port);
Address(const Address & src);
Address& operator=(const Address &src);
bool isNull();

friend std::ostream& operator<<(std::ostream& os, const Address& addr);
friend std::ostream& operator<<( const Address& addr, std::ostream& os);
};

std::ostream& operator<<( std::ostream& os, const Address& addr)
{
return os << " ( " << addr.addr << " : " << addr.port << " ) ";
}

int main()
{
Address a;
std::cout << a << std::endl;
}

这个输出:

 ( 0 : 0 ) 

看看这是否适合您,如果适合,只需回溯您的步骤,看看您的做法有何不同。

关于c++ - 蹩脚的运算符重新定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1896597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com