class1.h文件中: #ifndef CLASS1_H_ #define CLASS1_H_ #include <iostream> #include <string> class class1 { public: class class2 { public: class2(); class2(const class2 & src); class2& operator = (const class2 & rhs); private: double class2Value; std::string mString; mutable int mNumber = 0; }; class1(); class1(double value); ~class1(); private: double class1Value; }; #endif //CLASS1_H_ class1.cpp文件中: #include "class1.h" class1::class1() :class1Value(0.0) { } class1::class1(double value) :class1Value(value) { } class1::~class1() { } class1::class2::class2() :class2Value(0.0) ,mString("") { mNumber++; } class1::class2::class2(const class2 & src) { mNumber++; class2Value = src.class2Value; mString = src.mString; } class1::class2& class1::class2::operator = (const class2 & rhs) { if(this == &rhs) { return *this; } class2Value = rhs.class2Value; mString = rhs.mString; mNumber = rhs.mNumber; return *this; } 这里注意的是:在定义赋值运算符是的限定符class1::class2& class1::class2::operator = (const class2 & rhs)十分不便; 所以可以这样: 使用类别名称重命名,这样容易管理,在.cpp文件最上边定义:using sClass = class1::class2; #include "class1.h" using sClass = class1::class2; class1::class1() :class1Value(0.0) { } class1::class1(double value) :class1Value(value) { } class1::~class1() { } sClass::class2() :class2Value(0.0) ,mString("") { mNumber++; } sClass::class2(const class2 & src) { mNumber++; class2Value = src.class2Value; mString = src.mString; } sClass& sClass::operator = (const class2 & rhs) { if(this == &rhs) { return *this; } class2Value = rhs.class2Value; mString = rhs.mString; mNumber = rhs.mNumber; return *this; }