explicit
关键字在C++中意味着什么?
是否可以从另一个(在同一个类中,而不是从子类中)调用构造函数?如果有,怎么样?什么是调用另一个构造函数的最佳方法(如果有几种方法可以做到)?
如果我从一个基类继承并希望将继承类的构造函数中的某些东西传递给基类的构造函数,我该怎么做?
例如,
如果我从Exception类继承,我想做这样的事情:
class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
{
//This is where it's all falling apart
base(message);
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我想要的是能够将字符串消息传递给基本的Exception类.
我从ReSharper收到一条关于从我的对象构造函数调用虚拟成员的警告.
为什么不做这件事?
如果'Test'是一个普通的类,那么之间有什么区别:
Test* test = new Test;
Run Code Online (Sandbox Code Playgroud)
和
Test* test = new Test();
Run Code Online (Sandbox Code Playgroud) 我有两个构造函数,它们将值提供给只读字段.
public class Sample
{
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
_intField = i;
}
public Sample(int theInt) => _intField = theInt;
public int IntProperty => _intField;
private readonly int _intField;
}
Run Code Online (Sandbox Code Playgroud)
一个构造函数直接接收值,另一个构造函数进行一些计算并获取值,然后设置字段.
现在这里是抓住:
有任何想法吗?
作为C#开发人员,我习惯于运行构造函数:
class Test {
public Test() {
DoSomething();
}
public Test(int count) : this() {
DoSomethingWithCount(count);
}
public Test(int count, string name) : this(count) {
DoSomethingWithName(name);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在C++中执行此操作?
我尝试调用类名并使用'this'关键字,但都失败了.
我需要创建一个Set
初始值.
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
Run Code Online (Sandbox Code Playgroud)
有没有办法在一行代码中执行此操作?例如,它对最终的静态字段很有用.
我无法找到明确的答案.AFAIK,你不能__init__
在Python类中拥有多个函数.那么我该如何解决这个问题呢?
假设我有一个Cheese
使用该number_of_holes
属性调用的类.我怎样才能有两种创建奶酪对象的方法......
parmesan = Cheese(num_holes = 15)
number_of_holes
属性:gouda = Cheese()
我只想到一种方法来做到这一点,但这似乎有点笨重:
class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
Run Code Online (Sandbox Code Playgroud)
你说什么?还有另外一种方法吗?
从子类1调用超类构造函数的C++规则是什么?
例如,我知道在Java中,你必须将它作为子类构造函数的第一行(如果不这样做,则假定对no-arg超级构造函数的隐式调用 - 如果缺少则会给出编译错误) .
constructor ×10
c++ ×4
c# ×3
c++-faq ×2
inheritance ×2
java ×2
collections ×1
explicit ×1
hashset ×1
new-operator ×1
python ×1
resharper ×1
warnings ×1