sealed (C++/CLI и C++/CX)sealed (C++/CLI and C++/CX)
sealed — это контекстно-зависимое ключевое слово для ссылочных классов, которое означает, что виртуальный элемент нельзя переопределить или что тип не может использоваться в качестве базового типа.sealed is a context-sensitive keyword for ref classes that indicates that a virtual member cannot be overridden, or that a type cannot be used as a base type.
Примечание
В стандарте языка ISO C++11 представлено ключевое слово final.The ISO C++11 Standard language introduced the final keyword. Используйте final в стандартных классах, а sealed — в ссылочных классах.Use final on standard classes, and sealed on ref classes.
Все среды выполненияAll Runtimes
СинтаксисSyntax
ref class identifier sealed {...};
virtual return-type identifier() sealed {...};
ПараметрыParameters
identifieridentifier
Имя функции или класса.The name of the function or class.
Тип возвращаемого значенияreturn-type
Тип, который возвращается функцией.The type that's returned by a function.
КомментарииRemarks
В первом примере синтаксиса запечатан (sealed) класс.In the first syntax example, a class is sealed. Во втором примере запечатана виртуальная функция.In the second example, a virtual function is sealed.
Используйте ключевое слово sealed для ссылочных классов и их виртуальных функций-членов.Use the sealed keyword for ref classes and their virtual member functions. Дополнительные сведения см. в статье Спецификаторы переопределения и компиляция в машинный код.For more information, see Override Specifiers and Native Compilations.
Во время компиляции можно определить, запечатан ли тип, используя признак типа __is_sealed(type)
.You can detect at compile time whether a type is sealed by using the __is_sealed(type)
type trait. Дополнительные сведения см. в статье Compiler Support for Type Traits (C++/CLI and C++/CX) (Поддержка характеристик типов компилятором (C++/CLI and C++/CX)).For more information, see Compiler Support for Type Traits.
sealed — контекстно-зависимое ключевое слово.sealed is a context-sensitive keyword. Дополнительные сведения см. в статье Context-Sensitive Keywords (C++/CLI and C++/CX) (Контекстно-зависимые ключевые слова (C++/CLI и C++/CX)).For more information, see Context-Sensitive Keywords.
Среда выполнения WindowsWindows Runtime
См. статью о ссылочных классах и структурах.See Ref classes and structs.
ТребованияRequirements
Параметр компилятора: /ZW
Compiler option: /ZW
Среда CLRCommon Language Runtime
(Отсутствуют комментарии для этой возможности языка, которая применяется только в среде CLR).(There are no remarks for this language feature that apply to only the common language runtime.)
ТребованияRequirements
Параметр компилятора: /clr
Compiler option: /clr
ПримерыExamples
В следующем примере кода показано влияние sealed на виртуальный элемент.This following code example shows the effect of sealed on a virtual member.
// sealed_keyword.cpp
// compile with: /clr
interface struct I1 {
virtual void f();
virtual void g();
};
ref class X : I1 {
public:
virtual void f() {
System::Console::WriteLine("X::f override of I1::f");
}
virtual void g() sealed {
System::Console::WriteLine("X::f override of I1::g");
}
};
ref class Y : public X {
public:
virtual void f() override {
System::Console::WriteLine("Y::f override of I1::f");
}
/*
// the following override generates a compiler error
virtual void g() override {
System::Console::WriteLine("Y::g override of I1::g");
}
*/
};
int main() {
I1 ^ MyI = gcnew X;
MyI -> f();
MyI -> g();
I1 ^ MyI2 = gcnew Y;
MyI2 -> f();
}
X::f override of I1::f
X::f override of I1::g
Y::f override of I1::f
В следующем примере кода показано, как пометить класс запечатанным.The next code example shows how to mark a class as sealed.
// sealed_keyword_2.cpp
// compile with: /clr
interface struct I1 {
virtual void f();
};
ref class X sealed : I1 {
public:
virtual void f() override {}
};
ref class Y : public X { // C3246 base class X is sealed
public:
virtual void f() override {}
};
См. также разделSee also
Расширения компонентов для .NET и UWPComponent Extensions for .NET and UWP