使用委托构造函数时的成员初始化
Member initialization while using delegate constructor
C++ 标准不允许在单个 mem-initializer-list 中使用委托构造函数和成员初始化器,但以下代码可以使用 clang++ 和 g++ 进行编译。
#include <iostream>
class Shape {
public:
Shape();
};
class Circle : public Shape {
public:
std::string name;
Circle(std::string name);
};
Shape::Shape() {
std::cout << "Shape constructor" << std::endl;
}
Circle::Circle(std::string name) : Shape::Shape(), name(name) { /* <--- Expected an error here! */
std::cout << "Circle constructor" << std::endl;
}
int main() {
Circle c("my_circle");
std::cout << c.name << std::endl;
return 0;
}
C++ 20 标准的相关引用是(强调我的):
(§11.10.2/6) A mem-initializer-list can delegate to another constructor of the constructor’s class using any class-or-decltype that denotes the constructor’s class itself. If a mem-initializer-id designates the constructor’s class, it shall be the only mem-initializer; the constructor is a delegating constructor, and the constructor selected by the mem-initializer is the target constructor.[...]
我是不是误读了 C++ 标准?这里clang++和g++是否偏离标准?
您没有使用委托构造函数。
委托构造函数在同一个 class.
中调用另一个构造函数
例如,在:
struct Foo
{
Foo(int) : Foo("delegate") {} // #1
Foo(std::string) {} // #2
};
#1 和#2 都是Foo
的构造函数,并且构造函数#1 委托给构造函数#2。
在你的情况下,你有一个 class 派生自另一个 class,并且在:
Circle::Circle(std::string name) : Shape::Shape(), name(name)
您正在通过调用 Shape
的默认构造函数来初始化 Circle
对象的基础 Shape
部分。然后您继续完成初始化 Circle
class 的其余成员。这不是委托构造函数。
C++ 标准不允许在单个 mem-initializer-list 中使用委托构造函数和成员初始化器,但以下代码可以使用 clang++ 和 g++ 进行编译。
#include <iostream>
class Shape {
public:
Shape();
};
class Circle : public Shape {
public:
std::string name;
Circle(std::string name);
};
Shape::Shape() {
std::cout << "Shape constructor" << std::endl;
}
Circle::Circle(std::string name) : Shape::Shape(), name(name) { /* <--- Expected an error here! */
std::cout << "Circle constructor" << std::endl;
}
int main() {
Circle c("my_circle");
std::cout << c.name << std::endl;
return 0;
}
C++ 20 标准的相关引用是(强调我的):
(§11.10.2/6) A mem-initializer-list can delegate to another constructor of the constructor’s class using any class-or-decltype that denotes the constructor’s class itself. If a mem-initializer-id designates the constructor’s class, it shall be the only mem-initializer; the constructor is a delegating constructor, and the constructor selected by the mem-initializer is the target constructor.[...]
我是不是误读了 C++ 标准?这里clang++和g++是否偏离标准?
您没有使用委托构造函数。
委托构造函数在同一个 class.
中调用另一个构造函数例如,在:
struct Foo
{
Foo(int) : Foo("delegate") {} // #1
Foo(std::string) {} // #2
};
#1 和#2 都是Foo
的构造函数,并且构造函数#1 委托给构造函数#2。
在你的情况下,你有一个 class 派生自另一个 class,并且在:
Circle::Circle(std::string name) : Shape::Shape(), name(name)
您正在通过调用 Shape
的默认构造函数来初始化 Circle
对象的基础 Shape
部分。然后您继续完成初始化 Circle
class 的其余成员。这不是委托构造函数。