c++ - 使用方法而不是构造函数设置值的类的一行初始化

标签 c++ c++11

假设我有一个类 Test:

class Test {
public:
  int a;

  Test();
  int set(int a);
};

Test::Test() {}

int Test::set(int a) {
  this->a = a;
  return a;
}

这个类的实例可以用这样的值初始化(当然):

Test t;
t.set(10);

但是有没有办法在一行中做到这一点?以下代码不起作用

Test t.set(10);

我什么时候想这样做?

我正在使用游戏开发库 - SFML - 并且要将纹理应用于形状,我需要传递对 Texture 实例的引用,如下所示:

Texture texture;
texture.loadFromFile("mud.png");

rect.setTexture(&texture);

我想创建一个类,其中包含一些定义一些纹理的静态常量,然后我可以在其他地方使用它们。

最佳答案

您可以创建一个辅助 make 函数:

auto make_texture_from_file(const std::string& filename) -> Texture
{
    Texture texture;
    texture.loadFromFile(filename); 
    return texture;
}

关于c++ - 使用方法而不是构造函数设置值的类的一行初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45772405/

相关文章:

c++ - 在 C 或 C++ (mac OSX) 中拥有 KeyDown 事件

C++根据输入返回一个字符串或一个int

c++ - for 循环、读取和写入文件有困难

c++ - 最小实例化类对象,查询getInstance<T>()时,基于继承

c++ - 使用带有静态 constexpr 的模板类时如何修复链接错误?

c++ - 在VS2010 C++中解析 "found ' {' at file scope (missing function header?)"

c++ - 你能专攻 std::unique_lock 吗

c++ - 如何在 C++ 中对任何函数进行 typedef?

c++ - 获取对 std::list 中最后两个元素的引用

c++ - 按成员(member)值投