C++ 在c+中可能实现的强制转换+;
我的C++ 在c+中可能实现的强制转换+;,c++,C++,我的标题中有这段代码: class A { private: int player; public: A(int initPlayer = 0); A(const A&); A& operator=(const A&); ~A(); void foo() const; friend int operator==(const A& i, const A& member) const; }; 运营商的实施==
标题中有这段代码:
class A {
private:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
~A();
void foo() const;
friend int operator==(const A& i, const A& member) const;
};
运营商的实施==
我需要为我的代码的这一部分进行转换:
i-是我的函数接收的一些int
A*pa1=新的A(a2)
我收到一个错误非成员函数
,如何修复它?提前感谢您的错误与强制转换或用户定义的转换无关
您不能对非成员函数的函数进行常量限定,因此:
int operator==(const A& i, const A& member) const;
应该是这样的:
int operator==(const A& i, const A& member);
您的错误与强制转换或用户定义的转换无关
您不能对非成员函数的函数进行常量限定,因此:
int operator==(const A& i, const A& member) const;
应该是这样的:
int operator==(const A& i, const A& member);
从友元函数中删除常量限定符。友元函数不是成员函数,因此常量限定符没有意义。从友元函数中删除常量限定符。友元函数不是成员函数,因此常量限定符没有意义。有两种解决方案:
使operator==()
成为成员函数,而不是朋友:
接口:
class A {
private:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
~A();
void foo() const;
int operator==(const A& rhv) const;
};
int A::operator==(const A& rhv) const
{
return this->player == rhv.player;
}
实施:
class A {
private:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
~A();
void foo() const;
int operator==(const A& rhv) const;
};
int A::operator==(const A& rhv) const
{
return this->player == rhv.player;
}
如果你真的想把operator==()
作为朋友函数,只需删除const
限定符,就像其他文章中提到的那样
有两种解决方案:
使operator==()
成为成员函数,而不是朋友:
接口:
class A {
private:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
~A();
void foo() const;
int operator==(const A& rhv) const;
};
int A::operator==(const A& rhv) const
{
return this->player == rhv.player;
}
实施:
class A {
private:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
~A();
void foo() const;
int operator==(const A& rhv) const;
};
int A::operator==(const A& rhv) const
{
return this->player == rhv.player;
}
如果你真的想把operator==()
作为朋友函数,只需删除const
限定符,就像其他文章中提到的那样