// 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++问题)
发布于 2011-02-25 01:53:38
当我遇到这种情况时,我添加了一个用于初始化常用值的成员函数,例如在两个构造函数上调用的Init方法。
发布于 2011-02-25 01:53:50
使用方法
例如,将此方法命名为init()。
发布于 2011-02-25 02:08:38
Base()构造函数没有初始化value,我甚至不确定是否需要这个构造函数,因为它是private。
只需确保您充分定义了您的公共API,并且只创建了需要的构造函数。然后在每个构造函数中使用初始化器列表来分配所有属性,以避免使用未初始化的内存(通常尽量避免在主体或单独的方法中分配,以避免可能的双重初始化。
https://stackoverflow.com/questions/5108481
复制相似问题