结构与类

shu*_*jan 4 c++ structure class

// By using structure :     
struct complex {
  float real;
  float imag;
};    

complex operator+(complex, complex);    

main() { 
  complex t1, t2, t3;    
  t3 = t1 + t2;    
}    

complex operator+(complex w, complex z) {
  statement 1;    
  statement 2;   
}    

// By using class :    
class complex {
  int real;
  int imag;    

public:    
  complex operator+(complex c) {
    statement 1;    
    statement 2;    
  }    

  main() {    
    complex t1, t2, t3;    
    t3 = t1 + t2;    
  }    
Run Code Online (Sandbox Code Playgroud)

在使用结构时,重载函数可以接受两个参数,而在使用类时,重载函数只接受一个参数,当重载操作符函数在两种情况下都是成员函数时,即在struct和class中.为什么会这样?

Arm*_*yan 10

这与类和结构无关.这是关于成员与非成员.

C++中的类和结构区别仅仅是它们对于成员和基础的默认可访问性级别(对于结构体是公共的,对于类是私有的).除此之外,没有任何区别.

当重载运算符时,您几乎总是可以选择将运算符定义为成员或独立函数.只有4个运营商必须是会员.它们是:(),[],->,和=(至于为什么,看到我的这个问题).其余的,选择是你的.

这个优秀的FAQ条目解释了(除其他事项外)如何在成员与非成员之间做出选择.

回答你的核心问题:如果是成员函数,第一个文章是 *this