// Inheritance.cpp : main project file.
#include "stdafx.h"
using namespace System;
ref class Base {
private:
int value;
int value2;
Base() { this->value2 = 4; }
protected:
Base(int n) {
Base(); // <- here is my problem
value = n;
}
int get(){ return value; }
int get2(){ return value2; }
};
ref class Derived : Base {
public:
Derived(int n) : Base(n) { }
void println(){
Console::WriteLine(Convert::ToInt32(get()));
Console::WriteLine(Convert::ToInt32(get2()));
}
};
int main(array<System::String ^> ^args) {
Derived ^obj = gcnew Derived(5);
obj->println();
Console::ReadLine();
}
控制檯輸出:C++構造函數,繼承,訪問修飾符和東西
0
5
我知道,我做調用基()構造函數,並且我知道我創造這樣一個新的對象,在Base(int n)被調用後消失...
但我不知道如何將我的私有默認構造函數與受保護的構造函數結合起來。
(我使用通過視覺工作室2010年的.NET框架,但我認爲這更像是一個普通的C++的問題)
在C++中,您無法調用構造函數從一個構造函數:http://stackoverflow.com/questions/308276/c-call-constructor-from-constructor – birryree 2011-02-24 17:53:06
感謝您的鏈接 – Baarn 2011-02-24 18:07:38
@birryee:當然可以 - 但這樣做構造*另一個*對象,而不是委託 – 2011-02-24 18:32:53