// 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