2015-10-18 48 views
1

我有以下结构:如何在C++中重载赋值运算符?

struct mystruct{ 
    int a; 
    int b; 
    int c; 
} 

我只是想重载 “=”,使mystruct A = mystruct B 等于:

A.a = B.a; 
A.b = B.b; 
A.c = B.c; 

(场分别分配)

我应该怎么做它?

+0

请说明你正在使用什么编程语言。 –

+0

@RaymondChen我正在使用cpp –

+2

默认的赋值运算符按您的需要工作。即你不需要重载'='运算符。你有什么问题?你不知道如何做运算符重载?你有没有检查过C++的任何介绍书? –

回答

0
struct mystruct{ 
    int a; 
    int b; 
    int c; 

    mystruct& operator=(const mystruct& other) 
    { 
     a = other.a; 
     b = other.b; 
     c = other.c; 
     return *this; 
    } 
} 
0

自动生成的赋值操作符就像那样工作。但假设,这只是一个例子,你想要做其他事情,请考虑:

struct mystruct { 
    int a; 
    int b; 
    int c; 
    mystruct& operator=(const mystruct& other) { 
    this->a = other.a; 
    this->b = other.b; 
    this->c = other.c; 
    return *this; 
    } 
};