C++构造函数、继承、访问修饰符等等
// 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++ 问题)
// 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();
}
Console Output is:
0
5
i know, that i do call the Base() constructor, and i know that i create something like a new object, that vanishes after Base(int n) was called...
but i have no idea how i could combine my private default constructor with the protected one.
(i am using the .NET framework via visual-studio-2010, but i think this is more like a general c++ problem)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我遇到这种情况时,我添加了一个成员函数来初始化公共值,例如在两个构造函数上调用的 Init 方法。
When I face this situation I added a member function for initializing common values, like for example an Init method called on both constructors.
使用方法
例如,将此方法命名为
init()
。use method
name this method
init()
, for example.Base()
构造函数使value
未初始化,我什至不确定是否需要该构造函数,因为它是private
。只需确保您充分定义了公共 API 并且仅创建所需的构造函数。然后在每个构造函数中使用初始化列表来分配所有属性,以避免使用未初始化的内存(通常尝试避免在主体或单独的方法中分配,以避免可能的双重初始化。
The
Base()
constructor leavesvalue
uninitialized and I'm not even sure that constructor is needed at all since it'sprivate
.Just make sure that you adequately define your public API and only create constructors that are needed. Then in each constructor use the initializer list to assign all the attributes, to avoid working with uninitalized memory (typically try to avoid assigning in the body or a separate method to avoid possible double initialization.