繁体   English   中英

c ++如何为非默认构造类使用类初始化器

[英]c++ how to use class initialiser for a non default constructed class

我开始在 VS2019 (c++17) 中使用 SonarLint

我不知道如何为非默认构造的类使用类内初始化程序

class Foo
{
public:
  Foo(const std::string& str);
private:
  const std::string m_foostr;
};
Foo::Foo(const std::string& str) :
m_foostr(str)
{}

现在这里弹出 sonarlint 警告

class Bar
{
private:
 Foo m_foo;
};

Bar::Bar() : m_foo("something) ///< this produces a warning
{
}

Sonarlint 告诉我在类初始化器中使用https://rules.sonarsource.com/cpp/RSPEC-3230

怎样才能做到这一点? 我已经试过了

m_foo = Foo("something");

m_foo(Foo("something"));

两者都会导致编译器错误(可能是因为 m_foostr 是 const)。

你能帮我一下吗? 谢谢

编辑:根据要求:编译器错误是

第一个结果

Error C2280: attempting-to-reference-a-deleted-function

第二个结果是

Error 2064 term does not evaluate to a function taking N arguments

您尚未声明默认构造函数。 没有声明,您正在编写定义,这就是您收到第一个错误的原因。

class Bar
{
public:
    Bar();    
private:
 Foo m_foo;
};

Bar::Bar() : m_foo("something") ///< this produces a warning
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM