此聚合类中不调用构造函数
Constructor is not called in this aggregation class
class A {
public:
A() { cout << "A()" << endl; }
};
class B {
public:
A a;
B(const A& a1) : a(a1) { cout << "B(const A&)" << endl; }
/* B(const A& a1) { a = a1; cout << "B(const A&)" << endl; } */
};
int main() {
B b(A()); /* no ouput */
}
不会为上述代码生成任何输出。这是由于此链接中讨论的编译器优化(复制省略)吗?
但是如果我有一个 B 类构造函数并像下面这样重写代码:
class A {
public:
A() { cout << "A()" << endl; }
};
class B {
public:
A a;
B() {}
B(const A& a1) : a(a1) { cout << "B(const A&)" << endl; }
/* B(const A& a1) { a = a1; cout << "B(const A&)" << endl; } */
};
int main() {
B().a; // gives output A()
}
添加一对额外的括号:
B b((A()));
// you can also fix it using new C++11 initialization syntax:
B b{A()};
您面临的问题称为最烦人的解析,这意味着编译器无法决定您是需要函数声明还是变量定义。
[编辑]
我还应该补充一点,标准要求编译器在这种情况下选择函数声明。
[编辑]
在这种情况下,Clang 实际上更有帮助,并给出了使用部分的提示:
http://rextester.com/PECQ53431
source_file.cpp:16:8: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
B b(A()); /* no ouput */
^~~~~
source_file.cpp:16:9: note: add a pair of parentheses to declare a variable
B b(A()); /* no ouput */
^
( )
生成 1 条警告。
B b(A());
不明确,可以解释为变量声明或函数的声明,该函数返回类型为 B
的 restult,并采用没有参数的函数类型的单个未命名参数并返回类型 A
的结果。虽然你可能认为第一个应该发生,但标准规定实际上第二个会发生。请参阅维基百科中有关最烦人的解析的文章。
不要在创建 B 对象后创建 A 对象,而是在 main 中创建第一个 A s
对象。
A a;
B b(a);
相关文章:
- 在c++中使用向量时,如何调用构造函数和析构函数
- C++:考虑但不调用构造函数的特殊性
- 对象实例化调用构造函数的次数太多
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- C ++:通过大括号调用构造函数?
- 不能调用构造函数
- 赋值 boost::intrusive_ptr 而不调用构造函数?
- 在模板化类的构造函数中调用构造函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 我不明白在这个例子中什么时候调用构造函数
- 调用c++构造函数的不同方法
- 调用构造函数与将内联常量定义为默认参数
- 如何通过 Rust FFI 调用C++构造函数?
- "new"运算符是否总是调用构造函数?
- 无法调用构造函数
- 使用 "()" 调用构造函数不同于"{}"
- 确定是调用构造函数还是强制转换运算符的因素