gpt4 book ai didi

c++ - 使用成员作为参数调用构造函数解析为变量定义

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:44:06 25 4
gpt4 key购买 nike

我观察到 g++4.6.3 中的特殊行为。当通过调用类构造函数 File(arg) 创建临时文件时,编译器选择忽略 arg 的存在并将表达式解析为 File arg;

  • 为什么会忽略成员名称?
  • 标准是怎么说的?
  • 如何避免? (不使用新的 {} 语法)
  • 是否有相关的编译器警告? (我可以使用任意字符串 arg,它仍然可以安静地工作)

代码:

#include <iostream>

class File {
public:
explicit File(int val) : m_val(val) { std::cout<<"As desired"<< std::endl; }
File() : m_val(10) { std::cout<< "???"<< std::endl;}

private:
int m_val;
};

class Test {
public:
void RunTest1() { File(m_test_val); }
void RunTest2() { File(this->m_test_val); }
void RunTest3() { File(fhddfkjdh); std::cout<< "Oops undetected typo"<< std::endl; }
private:
int m_test_val;
};

int main()
{
Test t;
t.RunTest1();
t.RunTest2();
t.RunTest3();
return 0;
}

输出:

$ ???
$ As desired
$ Oops undetected typo

最佳答案

编译器处理该行:

File(m_test_val);

作为

File m_test_val;

所以您实际上是在使用默认构造函数创建一个名为 m_test_val 的命名对象。 File(fhddfkjdh) 也是如此。

解决方案是 File(this->m_test_val) - 这告诉编译器您要使用该成员来创建命名对象。另一种方法是命名对象 - File x(m_test_val)

关于c++ - 使用成员作为参数调用构造函数解析为变量定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12893339/

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