C++ 在堆栈上创建没有空无参数构造函数的类的新实例
可能的重复项:C++ 在堆栈上创建没有空无参数构造函数的类的新实例,c++,C++,可能的重复项: 我想知道使用无参数构造函数创建类的实例意味着什么 例如,如果我有一个类“a”,并尝试创建一个如下所示的变量: A myVariable() 我试着组织一个小项目来测试它: #include <iostream> using namespace std; class A { public: A(); A( int a, int b ); public: int mA; int mB
我想知道使用无参数构造函数创建类的实例意味着什么 例如,如果我有一个类“a”,并尝试创建一个如下所示的变量:
A myVariable()
我试着组织一个小项目来测试它:
#include <iostream>
using namespace std;
class A
{
public:
A();
A( int a, int b );
public:
int mA;
int mB;
private:
virtual void init( int a , int b );
};
A::A()
{
cout << "\tA()" << endl;
this->init( 0, 0 );
} // end of function A::A
A::A( int a, int b = 0 )
{
cout << "\tA( int a, int b )" << endl;
this->init( a, b );
} // end of function A::A
void A::init( int a, int b )
{
cout << "\tInit( int a, int b )" << endl;
mA = a;
mB = b;
} // end of function A::init
int main()
{
cout << "Start" << endl;
cout << "A myA0()" << endl;
A myA0();
cout << "A myA1" << endl;
A myA1;
cout << "A myA2( 0 )" << endl;
A myA2( 0 );
cout << "A myA3( 0, 0 )" << endl;
A myA3( 0, 0 );
cout << "Stop" << endl;
return 0;
}
所以它似乎没有调用任何构造函数。当我尝试在VisualStudio中单步遍历它时,它只是跳过它,就像它没有被编译一样。当我尝试打印出变量时,我得到一个未知的外部符号错误
注意:当然,当使用new运算符时,需要执行“new A()”,并将使用默认构造函数。语法:
A myA0();
不通过调用默认构造函数来创建a
类型的变量,而是声明一个不带参数并按值返回a
的函数。在标签中查找最烦人的解析或类似内容。要创建局部变量,只需执行以下操作:
A myA0; // no ()!!!
您必须注意的另一个问题是,从构造函数或析构函数调用的虚拟方法不会使用动态分派。对A
构造函数中init
的调用是对A::init
的调用,即使您正在构造从A
派生的B
类型的对象:
struct B : A {
void init( int, int ) { std::cout << "B::init(int,int)" << std::endl; }
};
int main() {
B b; // will print "\tInit( int a, int b )" from the constructor of `A`
b.init(); // will print "B::init(int,int)"
}
结构B:A{
void init(int,int){std::cout语法:
A myA0();
不通过调用默认构造函数来创建a
类型的变量,而是声明一个不带参数且按值返回a
的函数。在标记中查找最烦人的解析或类似内容。要创建局部变量,只需执行以下操作:
A myA0; // no ()!!!
您必须注意的另一个问题是,从构造函数或析构函数调用的虚拟方法不会使用动态分派。在A
构造函数中调用init
就是调用A::init
,即使您正在构造从A
派生的B
类型的对象:
struct B : A {
void init( int, int ) { std::cout << "B::init(int,int)" << std::endl; }
};
int main() {
B b; // will print "\tInit( int a, int b )" from the constructor of `A`
b.init(); // will print "B::init(int,int)"
}
结构B:A{
void init(int,int){std::cout这个问题已经被问了一百万次了。这只是一个寻找重复的问题。看看这个:还有这个:
a myA0();
定义了一个名为myA0
的函数,返回类型为a
,或者至少编译器是这么认为的-搜索“最麻烦的解析”。感谢所有评论。很抱歉,我尝试先搜索它,但不知道在搜索中使用什么语言。这个问题已经被问了一百万次。这只是找到副本的问题。看看这个:还有这个:a myA0();
定义了一个名为myA0
的函数,返回类型为a
——或者至少编译器是这么认为的——搜索“最烦人的解析”。感谢所有的评论。很抱歉,我先尝试搜索它,但不知道在搜索中使用什么语言。