friend complex operator+(const complex &A, const complex &B) const;
非成员函数不能是const,会报错1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class A { public: void fun1() { cout << a << endl; cout << "基类函数 fun1" << endl; } private: int a = 10; }; class B :public A { public:
private: int a = 20; }; int main(){ B b; b.fun1(); }
|
10
基类函数 fun1
输出的a
是基类名空间下的a
,而不是派生类名空间下的a
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class A { public: void fun1() { cout << a << endl; cout << "基类函数 fun1" << endl; } private: int a = 10; }; class B :public A { public: void fun1() { cout << a << endl; cout << "派生类函数 fun1" << endl; } private: int a = 20; }; int main(){ B b; b.fun1(); }
|
20
派生类函数 fun1
因为在派生类中定义了相同名字的函数和变量,所以基类名空间下的被隐藏了
demo3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
using namespace std;
class complex { public: complex();
complex(double real, double imag);
~complex(){ cout << "deconstruct" << endl; } public: complex operator+(const complex &A) const;
void display() const;
private: double m_real; double m_imag; };
complex::complex() : m_real(0.0), m_imag(0.0) {}
complex::complex(double real, double imag) : m_real(real), m_imag(imag) { cout << "construct" << endl;
}
complex complex::operator+(const complex &A) const { complex B; B.m_imag = this->m_imag + A.m_imag; B.m_real = this->m_real + A.m_real; return B; }
void complex::display() const { cout << m_real << " + " << m_imag << "i" << endl; }
int main() { complex c1(4.3, 5.8); complex c2(2.4, 3.7); complex c3; c3 = c1 + c2; c3.display();
return 0; }
|
为什么
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
#include <iostream>
using namespace std;
class complex { public: complex();
complex(double real, double imag);
~complex() { cout << "deconstruct" << endl; }
public:
friend complex operator+(const complex &A, const complex &B);
complex operator *(const complex &other)const; void display() const;
private: double m_real; double m_imag; };
complex::complex() : m_real(0.0), m_imag(0.0) {}
complex::complex(double real, double imag) : m_real(real), m_imag(imag) { cout << "construct" << endl; }
complex complex::operator*(const complex &A) const{ return complex(this->m_real * A.m_real, this->m_imag * A.m_imag); }
complex operator+(const complex &A, const complex &B) { complex C; C.m_real = A.m_real + B.m_real; C.m_imag = A.m_imag + B.m_imag; return C; }
void complex::display() const { cout << m_real << " + " << m_imag << "i" << endl; }
int main() { complex c1(4.3, 5.8); complex c2(1.0, 3.7); complex c3; c3 = c1 + c2 * c2; c3.display(); return 0; }
construct construct construct deconstruct deconstruct 5.3 + 19.49i deconstruct deconstruct deconstruct
|