gpt4 book ai didi

C++11 成员初始化列表歧义

转载 作者:IT老高 更新时间:2023-10-28 12:38:31 25 4
gpt4 key购买 nike

由于此环境中的 GNU 标准库实现,我正在努力解决 c++11 符号解析中似乎存在歧义的问题:

  • Arch Linux 4.2.5-1 (x86_64)
  • g++ 5.2.0
  • clang++ 3.7.0

例子:

#include <iostream>
#include <string>

struct version {

unsigned major;
unsigned minor;
unsigned patch;

version(unsigned major, unsigned minor, unsigned patch) :
major(major), minor(minor), patch(patch) { }

friend std::ostream & operator<<(std::ostream & out, version const& v) {
out << v.major << ".";
out << v.minor << ".";
out << v.patch;
return out;
}

};

int main(int argc, char ** argv) {
version v(1, 1, 0);
std::cout << v << std::endl;
return 0;
}

编译器错误:

error: member initializer 'gnu_dev_major' does not name a non-static data
member or base class
error: member initializer 'gnu_dev_minor' does not name a non-static data
member or base class

命令:

clang++ -std=c++11 -o test *.cpp

范围解析运算符似乎不适用于成员初始化列表,因此我无法弄清楚如何解决歧义。此示例在没有 c++11 标志的情况下编译良好。

最佳答案

另一种方法是使用大括号:

version(unsigned major, unsigned minor, unsigned patch) :
major{major}, minor{minor}, patch{patch} { }

那么宏就不会干扰了,因为它们是类函数宏,需要括号才能调用。

关于C++11 成员初始化列表歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com