class A{
A(int a = 5){
DoSomething();
A();
}
A(){...}
}
第一个构造函数可以调用第二个构造函数吗?
class A{
A(int a = 5){
DoSomething();
A();
}
A(){...}
}
第一个构造函数可以调用第二个构造函数吗?
不是C++11之前的语法。
将常见功能提取到单独的函数中。我通常将此函数命名为construct()。
"所谓"的第二次调用会编译通过,但在C++中具有不同的含义:它将构造一个新对象,即临时对象,然后在语句结束时立即删除。因此,不行。
然而,析构函数可以无问题地被调用。
在 C++0x
之前是不可能的。
但是,出于学术兴趣,我想到了一种非常可怕的方法*,使用放置 new 运算符(有人能指出这种方法的可移植性吗?)
#include <new>
#include <iostream>
class A
{
public:
A(int i, int j)
: i_(i), j_(j) { }
A(int i)
{ new (this) A(i, 13); }
int i_,j_;
};
int
main() {
A a1(10,11), a2(10);
std::cout
<< a1.i_ << ", "
<< a1.j_ << std::endl
<< a2.i_ << ", "
<< a2.j_ << std::endl;
return 0;
}
*天哪,我不会在生产代码中写这个。
struct B {
B() {}
B( int x ) {}
};
struct A : public B {
A() {} // calls B() implicitly
A( int a, int b ) : B( b ) {} // calls B(int) explicitly
};
不能直接实现。有几种方法可以解决这个问题。
从类构造函数的初始化列表中,您可以调用任何基类和所有成员变量的构造函数。
因此,通常可以将类重构并将其拆分为几个较小的类来解决问题。常见执行的代码可以放置在成员对象或基类中。然后,每个主类的构造函数只需决定使用哪个构造函数来初始化该成员。
class B {
B() { }
B(int b) { DoSomething(); }
}
class A{
A(int a = 5) : b(a) { } // call B's constructor which does something
A() : b() {} // call B's constructor which does nothing
B b;
};
这是一个老问题了;然而,
在IT技术领域仍然备受关注。class A{
A(int a = 5){
DoSomething();
A();
}
A(){...}
}
可能是
class A{
A(int a = 5){
*this = A();
DoSomething();
}
A(){...}
}
*this = A();
会使用默认的复制构造函数(如果你没有定义的话),这可能不是你想要的结果? - austinmartonclass A
{
public:
A()
{
foo();
}
A(Attribute attribute) : A()
{
this->attribute = attribute;
}
//------ some other code --------
private:
Attribute attribute;
void foo()
{...}
//------ some other code -------
};