Visual C++ .NET/Class/Inheritance

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Call a Base Method

 
#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
class Base {
public:
    virtual ~Base() {
        Console::WriteLine("Base cleanup");
    };
};
class Derived : public Base {
public:
    virtual ~Derived() {
        Console::WriteLine("Derived cleanup");
    };
};
int main(void) {
    Derived instance;
    return 0;
}


Derive a Class

 
#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
class BaseClass {
public:
    virtual void MyFunction() {
        Console::WriteLine("Inside Base class");
    }
};
class DerivedClass : public BaseClass {
public:
    virtual void MyFunction() {
        Console::WriteLine("Inside Derived class");
    }
};
void main() {
    BaseClass base;
    DerivedClass derived;
    base.MyFunction();
    derived.MyFunction();
}


Finalizers and inheritance

 
#include "stdafx.h"
using namespace System;
ref class Base
{
   public:
     Base() { }
     ~Base() {  Console::WriteLine("~Base"); this->!Base(); }
     !Base() {  Console::WriteLine("!Base"); }
};
ref class Derived : Base
{
   public:
     Derived() { }
     ~Derived() {  Console::WriteLine("~Derived"); this->!Derived(); }
     !Derived() {  Console::WriteLine("!Derived"); }
};
void F()
{
   Derived d;
}
void G()
{
   Derived^ dh = gcnew Derived();
}
int main()
{
   F();
   G();
   Console::WriteLine("Collecting after G()");
   GC::Collect();
}


Inherit a class

 
#include "stdafx.h"
using namespace System;
ref class Square{
public:
    int Area(){
        return Dims * Dims;
    }
    int Dims;
};
ref class Cube : public Square{
public:
    int Volume(){
        return Area() * Dims;
    }
};
void main()
{
    Cube ^cube = gcnew Cube(); 
    cube->Dims = 3;
    Console::WriteLine(cube->Dims); 
    Console::WriteLine(cube->Area());
    Console::WriteLine(cube->Volume());
}