在c++中可以继承结构吗?
当前回答
除了Alex和Evan已经说过的,我想补充一点,c++结构体与C结构体不同。
在c++中,结构体可以像c++类一样具有方法、继承等。
其他回答
是的,struct和class完全一样,除了struct的默认可访问性是公共的(而class是私有的)。
除了Alex和Evan已经说过的,我想补充一点,c++结构体与C结构体不同。
在c++中,结构体可以像c++类一样具有方法、继承等。
在c++中,结构的继承和类的继承是一样的,除了以下不同之处:
从类/结构派生结构时,基类/结构的默认访问说明符为public。在派生类时,默认的访问说明符是私有的。
例如,程序1因编译错误而失败,而程序2正常工作。
// Program 1
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // Is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // Compiler error because inheritance is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Base {
public:
int x;
};
struct Derived : Base { }; // Is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // Works fine because inheritance is public
getchar();
return 0;
}
是的。默认情况下,继承是公共的。
语法(示例):
struct A { };
struct B : A { };
struct C : B { };
当然可以。在c++中,结构体和类几乎是相同的(比如默认为public而不是private就是其中的微小区别)。