最近让C ++和SDL2进行编译,并开始四处乱搞。我已经非常了解Lua和JavaScript,并且可以毫无问题地完成大多数我需要做的事情。
我希望创建一个对象,该对象可以实现类似Lua的示例,但是使用C ++。我无法在线上找到任何东西,但是我可能没有使用正确的搜索词,因为我是C ++的新手(尽管我有一定的C经验)。
foo = {
a = 0,
b = "hello"
c = "world"
}
function foo:bar(baz)
self.a = self.a + 1
print(self.b.." "..self.c)
table.insert(self, baz)
end
非常感谢您的帮助!
从a good book开始学习C ++较容易,而不是立即尝试自己玩C ++。 C ++不像Lua那样容错。
仍然,这是一些类似于您的Lua示例的C ++代码:
// Makes the standard type std::string available:
#include <string>
// Every variable needs a type.
// "class" creates a new type with given members, so here's how we'll define
// a type for variable "foo".
// A class definition like this usually goes in a header file.
class FooType
{
public:
// These members have default initializers, which will be used when
// a FooType object is created without its own initializer.
int a = 0;
std::string b = "hello";
std::string c = "world";
// This declares a class member function named bar, returning nothing:
void bar();
};
// The actual variable foo:
FooType foo;
// Defining the member function called FooType::bar :
// This might go in a source file which begins with an #include of
// the corresponding header file.
#include <iostream> // to get std::cout and std::endl
void FooType::bar()
{
// self.a = self.a + 1 :
// The C++ keyword "this" is similar to Lua's "self", but is a pointer.
// All of these are equivalent:
// (*this).a = (*this).a + 1;
// this->a = this->a + 1;
// a = a + 1; // C++ automatically adds an implicit "this->" when you
// just name a member.
// ++a; // A shortcut for adding one to a number.
++a;
// print(self.b.." "..self.c) :
std::cout << b << " " << c << std::endl;
// Lua's print automatically adds a newline after its data, but
// C++ std::cout does not. The std::endl adds a newline and then
// "flushes" the output, making sure it gets sent out more or less
// immediately instead of waiting for more data as an optimization.
// table.insert(self, baz) :
// Not possible - C++ does not allow adding members to a class which
// aren't declared in the class definition. If you really need something
// similar, you could use a map with name as the key, but then you would
// need to access all those "members" via that map, not with a plain
// obj.name expression.
}
一些注意事项:
在Lua中,冒号方法语法只是一个快捷方式。也就是说,foo:bar(t)
与foo.bar(foo, t)
完全相同,但是Lua会让您做类似foo.bar(0, t)
的奇怪事情,这意味着self
变量变为0
。 (这当然可能违反bar
方法的隐含约定!)在C ++中,编译器通常会实现成员函数,就好像它们是具有this
附加参数的普通函数一样,但是就语言而言,成员函数与非成员函数完全不同,并且调用它的唯一方法都涉及正确类型的对象成为*this
。
相关,Lua让您重新分配self
,但C ++不允许您更改指针this
。
Lua用“引用语义”对待表,但是在C ++中,默认值是所有变量都使用“值语义”。
-- Lua:
foo2 = foo -- Another name for the same table.
foo2.a = 3 -- foo.a is now 3.
// C++ (within a function):
FooType foo2 = foo; // A different independent object.
foo2.a = 3; // foo2.a is 3, but foo.a is unchanged
FooType& foo3 = foo; // Another name for object foo.
foo3.a = 4; // foo.a is now 4.