c++内嵌子对象和c++内嵌子类的区别
C++内嵌子对象和内嵌子类是两种不同的概念。
内嵌子对象是指在一个类的定义中,将另一个类的对象作为成员变量嵌入其中。这样做的好处是可以在外部类中直接使用嵌入对象的成员函数和数据,而不必对其进行额外的引用或指针操作。例如:
class A {
public:
A(int x) : m_x(x) {}
int getX() const { return m_x; }
private:
int m_x;
};
class B {
public:
B() : m_a(42) {}
int getAX() const { return m_a.getX(); }
private:
A m_a;
};
int main() {
B b;
std::cout << b.getAX() << std::endl; // 输出 42
}
内嵌子类则是在一个类的定义中,定义一个新的类作为其成员,这个新的类只有在外部类的作用域中才有意义。内嵌子类可以访问外部类的成员,而外部类也可以访问内嵌子类的成员。例如:
class A {
public:
A(int x) : m_x(x) {}
int getX() const { return m_x; }
class B {
public:
B() : m_a(42) {}
int getAX() const { return m_a.getX(); }
private:
A m_a;
};
private:
int m_x;
};
int main() {
A::B b;
std::cout << b.getAX() << std::endl; // 输出 42
}
可以看到,内嵌子类与内嵌子对象的最大区别在于内嵌子类可以定义自己的成员函数和变量,而内嵌子对象只能使用被嵌入对象的成员函数和变量
原文地址: https://www.cveoy.top/t/topic/eOr4 著作权归作者所有。请勿转载和采集!