Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 重载类外的赋值运算符_C++_Operator Overloading - Fatal编程技术网

C++ 重载类外的赋值运算符

C++ 重载类外的赋值运算符,c++,operator-overloading,C++,Operator Overloading,我一直在尝试使用friend类在类外重载赋值运算符,但无论我做什么,它都不起作用。(是的,我知道惯例是重载类内的操作符)。以下是我一直在做的工作示例: class Person{ public: Person(string n){ name = n; } friend class assignment; name = "Joe"; } } class assignment{ public: Person operator&(Person &rhs){

我一直在尝试使用friend类在类外重载赋值运算符,但无论我做什么,它都不起作用。(是的,我知道惯例是重载类内的操作符)。以下是我一直在做的工作示例:

class Person{

public:

Person(string n){
     name = n;
}

friend class assignment;

name = "Joe";

}


}

class assignment{
public:
Person operator&(Person &rhs){
        Person test;
        test.name = rhs.name;
        return test;  //return *this doesn't work

        }
}
无论我做什么,赋值运算符都不会在main中运行/返回:

Person one("Joe")
person two("Martin");
person three("Anna")

two = three;

std::cout<<two.name; //does not equal the member variable of three;
第一人称(“乔”)
第二人(“马丁”);
第三人(“安娜”)
二等于三;

std::cout忽略代码并切入问题的核心,如注释中所述:我只是想知道是否有可能在类外重载赋值运算符。答案是否定的

[class.copy.assign]明确禁止使用。目前我手头只有n4618,因此我将引用以下内容:

用户声明的复制赋值运算符
X::operator=
是类
X
非静态非模板成员函数,只有一个类型为
X
X&
常量X&
的参数


您可以做各种各样的事情来解决这个问题,但它们不是赋值运算符。

不要将硬语言规则降级为纯粹的约定。你只是没有,也不能。那是无法编译的。你发布的内容似乎没有任何意义。你能解释一下你的逻辑吗?我只是想知道是否有可能在类外重载赋值运算符。是吗?@anonanon不,不是