【发布时间】:2011-02-24 17:49:47
【问题描述】:
// 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();
}
控制台输出是:
0
5
我知道,我确实调用了 Base() 构造函数,并且我知道我创建了一个类似新对象的东西,它在 Base(int n) 被调用后消失了......
但我不知道如何将我的私有默认构造函数与受保护的构造函数结合起来。
(我通过visual-studio-2010使用.NET框架,但我认为这更像是一个一般的c++问题)
【问题讨论】:
-
在 C++ 中不能从构造函数调用构造函数:stackoverflow.com/questions/308276/…
-
@birryee:当然可以——但这样做会构造 另一个 对象,而不是将当前对象的构造委托给另一个构造函数。
-
是的,这正是我的问题:/
标签: .net visual-studio-2010 visual-c++ inheritance c++-cli