Lame运算符重定义错误

时间:2009-12-13 14:00:38

标签: c++

对不起它很蹩脚,但我无法理解:

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"应该工作!!!

2 个答案:

答案 0 :(得分:1)

以下代码在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 ) 

看看这是否适合您,如果确实如此,只需追溯您的步骤,看看您的行为有何不同。

答案 1 :(得分:0)

好吧,如果我包括

#include <cstdint>
#include <iostream>

在代码的开头,我可以使用g++ -c -std=c++0x Account.cpp(g ++ 4.4.1)编译它。